!ifndef REPLACEFILE_INCLUDED

!define ReplaceFILE_INCLUDED

; Macro - Replace File
; Written by Michael Sonst
; as an addition to Joost Verburg's "Upgrade a DLL"
; ------------------------
;
; Parameters:
; LOCALFILE   - Location of the new file (on the compiler system)
; DESTFILE    - Location of the file that should be Replaced (on the user's system)
; TEMPBASEDIR - Directory on the user's system to store a temporary file when the system has
;               to be rebooted.
;               For Win9x support, this should be on the same volume as the DESTFILE!
;               The Windows temp directory could be located on any volume, so you cannot use
;               this directory.
;
;
; Note: If you want to support Win9x, you can only use short filenames (8.3).
;
; Example of usage:
; !insertmacro ReplaceFile "exename.exe" "$SYSDIR\exename.exe" "$SYSDIR"
;

!macro ReplaceFile LOCALFILE DESTFILE TEMPBASEDIR

  Push $R0
  Push $R1
  Push $R2
  Push $R3
  Push $R4
  Push $R5

  ;------------------------
  ;Unique number for labels

  !define REPLACEFILE_UNIQUE ${__LINE__}
  
  ;------------------------
  ;Copy the parameters used on run-time to a variable
  ;This allows the usage of variables as paramter

  StrCpy $R4 "${DESTFILE}"
  StrCpy $R5 "${TEMPBASEDIR}"
  
  ;------------------------
  ;Check file

  IfFileExists $R4 0 Replacefile.copy_${REPLACEFILE_UNIQUE}
    
  ;------------------------
  ;Let's Replace the FILE!

  SetOverwrite try

  Replacefile.Replace_${REPLACEFILE_UNIQUE}:
  
  ClearErrors
    StrCpy $R0 $R4
    Call :Replacefile.file_${REPLACEFILE_UNIQUE}
  IfErrors 0 Replacefile.noreboot_${REPLACEFILE_UNIQUE}

  ;------------------------
  ;FILE is in use. Copy it to a temp file and Rename it on reboot.

  GetTempFileName $R0 $R5
    Call :Replacefile.file_${REPLACEFILE_UNIQUE}
  Rename /REBOOTOK $R0 $R4
  
  Goto Replacefile.done_${REPLACEFILE_UNIQUE}


  ;------------------------
  ;FILE does not exist - just extract

  Replacefile.copy_${REPLACEFILE_UNIQUE}:
    StrCpy $R0 $R4
    Call :Replacefile.file_${REPLACEFILE_UNIQUE}

  Replacefile.noreboot_${REPLACEFILE_UNIQUE}:
  ;------------------------
  ;Done

  Replacefile.done_${REPLACEFILE_UNIQUE}:

  Pop $R5
  Pop $R4
  Pop $R3
  Pop $R2
  Pop $R1
  Pop $R0

  ;------------------------
  ;End

  Goto Replacefile.end_${REPLACEFILE_UNIQUE}

  ;------------------------
  ;Called to extract the file

  Replacefile.file_${REPLACEFILE_UNIQUE}:
    File /oname=$R0 "${LOCALFILE}"
    Return

  Replacefile.end_${REPLACEFILE_UNIQUE}:

 ;------------------------
 ;Restore settings

 SetOverwrite lastused


  !undef REPLACEFILE_UNIQUE
!macroend

!endif