!include WinMessages.nsh
!include NSISdl.nsh

## Program related info
!define DATE      "24th August 2003, 11:34AM GMT"
!define L_VERSION "1.0.2.0"
!define VERSION   "v1.00"
!define BETA      "b2"
!define NAME      "D-Day Updater - ${VERSION}${BETA}"
Name              "${NAME}"
Caption           "${NAME}"

## Settings dialog version (du_settings)
!define DIALOG_VERSION "1"

## Urls
!define WEBSITE_URL         "http://supernova.servequake.com/ddma"
!define MAP_LIST_URL        "http://supernova.servequake.com/ddma/maplist.txt"
!define OBJECTS_URL1        "http://myweb.tiscali.co.uk/imker/ddayupdater/du_objects.txt"
!define OBJECTS_URL2        "http://supernova.servequake.com/ddma/files/du_objects.txt"
!define UPDATE_FILE_URL1    "http://myweb.tiscali.co.uk/imker/ddayupdater/ddayupdater.exe"
!define UPDATE_FILE_URL2    "http://supernova.servequake.com/ddma/files/ddayupdater.exe"

## Messages / stuff
!define ERROR_MSG1         "Error: No updates list found. See readme for trouble-shooting."
!define ERROR_MSG2         "Warning: The current updates list is not up-to-date."
!define ERROR_MSG3         "Error: Unable to get recommended item detection information."
!define ERROR_MSG4         "Error: Was unable to download D-Day Updater application update!"
!define ERROR_MSG5         "Error: Was unable to retrieve update information!$\r$\nRetry?"
!define ERROR_MSG6         "Error: Cannot connect to updates server.$\r$\nPlease make sure that you are connected to the internet."
!define ERROR_MSG7         "Error: D-Day Updater must be run from within the D-Day: Normandy game directory$\r$\n(e.g. C:\games\quake2\dday)"
!define ERROR_MSG8         "Error: D-Day Updater's vital information list could not be retrieved all internet locations.$\r$\nPlease check that you are connected to the internet before running D-Day Updater."

!define MISC_MSG1          "There are no downloads required. You are up-to-date!"
!define MISC_MSG2          "D-Day Updater detected an application update on the Internet.$\r$\nWould you like to download and install this update now?"

!define MISC_MSG3          "erm, we'll get back to you"

## Bitmaps
!define BITMAP_LEFT0       "left_logos\logo1.bmp"
!define BITMAP_LEFT1       "left_logos\logo2.bmp"
!define BITMAP_LEFT2       "left_logos\logo3.bmp"
!define BITMAP_LEFT3       "left_logos\logo4.bmp"
!define BITMAP_LEFT4       "left_logos\logo5.bmp"
!define BITMAP_TOP         "logo.bmp"

## Map counts
!define BSPS    $R8
!define ZIPS    $R9
!define ALLBSPS $R6
!define ALLZIPS $R7
!define MAPLIST $R8
!define FAILS   $1
!define CANCELS $2

## Header colour (html = 667799)
!define HEADER_COLOUR "0x00997766"

## Pages
Page Custom Settings "" ""
Page Custom MainDialog "" " - Download detected updates"
Page InstFiles

## General settings
SubCaption /LANG=English 3 " - Downloading..."
SubCaption /LANG=English 4 " - Process Finished"

ChangeUI all "${NSISDIR}\Contrib\UIs\modern.exe"
ChangeUI IDD_INST "${NSISDIR}\Contrib\UIs\modern_headerbmp.exe"
AddBrandingImage left 150 0

InstallColors "FFFFFF" "667799"
ShowInstDetails "show"
CompletedText "Process finished"

Icon "dday3.ico"
XPStyle "on"

BrandingText /TRIMRIGHT "D-Day Updater by Afrow UK"

InstallButtonText /LANG=English "Go! >"
MiscButtonText "Settings" "Next >" "Close" "Exit"

OutFile "ddayupdater.exe"

## Version information
VIProductVersion "${L_VERSION}"
VIAddVersionKey "ProductName" "D-Day Updater by Afrow UK"
VIAddVersionKey "Comments" "D-Day Updater is an application designed to update D-Day: Normandy, the Quake2 modification (http://www.planetquake.com/dday)."
VIAddVersionKey "LegalTrademarks" "D-Day Updater is a trademark of Afrow UK (lol)"
VIAddVersionKey "LegalCopyright" "© Afrow UK"
VIAddVersionKey "FileDescription" "D-Day Updater ${VERSION}${BETA}"
VIAddVersionKey "FileVersion" "${L_VERSION}"
VIAddVersionKey "File Name" "ddayupdater.exe (${__FILE__} build)"
VIAddVersionKey "Last Compile" "${__DATE__} at ${__TIME__}"



# //============================
# // Functions & Macros


# // Macro for making header
# // ===========================
!macro HEADER_TEXT TEXT SUBTEXT
  Push $2
  Push $1
  Push $0

	GetDlgItem $2 $HWNDPARENT 1037
	SendMessage $2 ${WM_SETTEXT} 0 "STR:${TEXT}"
	GetDlgItem $0 $HWNDPARENT 1038
	SendMessage $0 ${WM_SETTEXT} 0 "STR:${SUBTEXT}"
	CreateFont $1 Verdana 10 700
	SendMessage $2 ${WM_SETFONT} $1 0
	GetDlgItem $2 $HWNDPARENT 1037
	SetBkColor $2 "${HEADER_COLOUR}"
	GetDlgItem $2 $HWNDPARENT 1038
	SetBkColor $2 "${HEADER_COLOUR}"
	GetDlgItem $2 $HWNDPARENT 1039
	SetBkColor $2 "${HEADER_COLOUR}"
	GetDlgItem $2 $HWNDPARENT 1034
	SetBkColor $2 "${HEADER_COLOUR}"

  Pop $0
  Pop $1
  Pop $2
!macroend


# // For outputting selected downloads
# // ===========================
Function SplitFirstStrPart1
  Exch $R0
  Push $R1
  Push $R2
  StrLen $R1 $R0
  IntOp $R1 $R1 + 1
  loop:
    IntOp $R1 $R1 - 1
    StrCpy $R2 $R0 1 -$R1
    StrCmp $R1 0 exit0
    StrCmp $R2 "|" exit1 loop ; Change " " to "\" if ur inputting dir path str
  exit0:
  StrCpy $R1 ""
  Goto exit2
  exit1:
    IntOp $R1 $R1 - 1
    StrCpy $R2 $R0 "" -$R1
    IntOp $R1 $R1 + 1
    StrCpy $R0 $R0 -$R1
    StrCpy $R1 $R2
  exit2:
  Pop $R2
  Exch $R1 ;rest
  Exch
  Exch $R0 ;first
FunctionEnd


# // For outputting selected downloads
# // ===========================
Function SplitFirstStrPart2
  Exch $R0
  Push $R1
  Push $R2
  StrLen $R1 $R0
  IntOp $R1 $R1 + 1
  loop:
    IntOp $R1 $R1 - 1
    StrCpy $R2 $R0 1 -$R1
    StrCmp $R1 0 exit0
    StrCmp $R2 ";" exit1 loop ; Change " " to "\" if ur inputting dir path str
  exit0:
  StrCpy $R1 ""
  Goto exit2
  exit1:
    IntOp $R1 $R1 - 1
    StrCpy $R2 $R0 "" -$R1
    IntOp $R1 $R1 + 1
    StrCpy $R0 $R0 -$R1
    StrCpy $R1 $R2
  exit2:
  Pop $R2
  Exch $R1 ;rest
  Exch
  Exch $R0 ;first
FunctionEnd


# // Replace text in a string
# // ===========================
Function StrReplace
  Exch $0 ;this will replace wrong characters
  Exch
  Exch $1 ;needs to be replaced
  Exch
  Exch 2
  Exch $2 ;the orginal string
  Push $3 ;counter
  Push $4 ;temp character
  Push $5 ;temp string
  Push $6 ;length of string that need to be replaced
  Push $7 ;length of string that will replace
  Push $R0 ;tempstring
  Push $R1 ;tempstring
  Push $R2 ;tempstring
  StrCpy $3 "-1"
  StrCpy $5 ""
  StrLen $6 $1
  StrLen $7 $0
  Loop:
  IntOp $3 $3 + 1
  StrCpy $4 $2 $6 $3
  StrCmp $4 "" ExitLoop
  StrCmp $4 $1 Replace
  Goto Loop
  Replace:
  StrCpy $R0 $2 $3
  IntOp $R2 $3 + $6
  StrCpy $R1 $2 "" $R2
  StrCpy $2 $R0$0$R1
  IntOp $3 $3 + $7
  Goto Loop
  ExitLoop:
  StrCpy $0 $2
  Pop $R2
  Pop $R1
  Pop $R0
  Pop $7
  Pop $6
  Pop $5
  Pop $4
  Pop $3
  Pop $2
  Pop $1
  Exch $0
FunctionEnd


# // Get number of selected items
# // ===========================
Function ItemCount
Exch $R0 ;input string
Push $R1
Push $R2
Push $R3
Push $R4
 StrCpy $R1 0
 StrLen $R2 $R0
loop:
 IntOp $R1 $R1 + 1
  StrCpy $R3 $R0 1 -$R1
 StrCmp $R1 $R2 exit
 StrCmp $R3 "|" 0 loop
  IntOp $R4 $R4 + 1
Goto loop
exit:
StrCpy $R0 $R4
Pop $R4
Pop $R3
Pop $R2
Pop $R1
Exch $R0 ;output
FunctionEnd


# // Clear log win
# // ===========================
Function ClearDetails
  Push $0
  FindWindow $0 "#32770" "" $HWNDPARENT
  GetDlgItem $0 $0 1016
  SendMessage $0 0x1009 0 0
  Pop $0
FunctionEnd


# // Get map chunks
# // ===========================
Function AdvStrSort
  Exch $0 ; input string
  Exch
  Exch $1 ; count to get part
  Exch
  Exch 2
  Exch $2 ; get ammount of chunks from end
  Exch 2
  Push $3
  Push $4
  Push $5
  Push $6
  Push $7
  StrCpy $0 " $0"
  StrCpy $3 0
  StrCpy $4 0
  loop:
    IntOp $3 $3 - 1
    StrCpy $6 $0 1 $3
    StrCmp $6 "" skip
    StrCmp $6 "|" roger ; to change chunk seperators, edit this (" ")
    Goto loop
  roger:
    StrCpy $7 $0 "" $3
    IntOp $4 $4 + 1
    StrCmp $4 $2 0 loop
    StrCmp $1 $2 0 +3
    StrCpy $0 $7
    Goto end
  skip:
    StrCpy $4 0
    StrLen $5 $7
  top:
    IntOp $4 $4 + 1
  loop2:
    IntOp $5 $5 - 1
    StrCpy $3 $7 1 -$5
    StrCmp $3 "" end
    StrCmp $3 "|" 0 loop2 ; to change chunk seperators, edit this too (" ")
    StrCmp $4 $1 0 top
    StrCpy $0 $7 -$5
  end:
    StrLen $1 $0
    IntOp $1 $1 - 1
    StrCpy $0 $0 $1 -$1
  Pop $7
  Pop $6
  Pop $5
  Pop $4
  Pop $3
  Pop $2 
  Pop $1
  Exch $0 ; output string
FunctionEnd


# // Writes text to log
# // ===========================
Function WriteToFile
 Exch $0 ;file to write to
 Exch
 Exch $1 ;text to write

  FileOpen $0 $0 a #open file

 Push $1 #store $1

 #go to file end
 loop:
  ClearErrors
   FileRead $0 $1
    IfErrors 0 loop

 Pop $1 #renew $1

   FileWrite $0 "$1$\r$\n" #write to file
  FileClose $0

 Pop $1
 Pop $0
FunctionEnd


# // Get file size
# // ===========================
Function FileSizeNew
Exch $0
Push $1
  FileOpen $1 $0 r
  FileSeek $1 0 END $0
  FileClose $1
Pop $1
Exch $0
FunctionEnd


# // Searches in a string
# // ===========================
Function StrStr
  Exch $R1 ; st=haystack,old$R1, $R1=needle
  Exch    ; st=old$R1,haystack
  Exch $R2 ; st=old$R1,old$R2, $R2=haystack
  Push $R3
  Push $R4
  Push $R5
  StrLen $R3 $R1
  StrCpy $R4 0
  ; $R1=needle
  ; $R2=haystack
  ; $R3=len(needle)
  ; $R4=cnt
  ; $R5=tmp
  loop:
    StrCpy $R5 $R2 $R3 $R4
    StrCmp $R5 $R1 done
    StrCmp $R5 "" done
    IntOp $R4 $R4 + 1
    Goto loop
  done:
  StrCpy $R1 $R2 "" $R4
  Pop $R5
  Pop $R4
  Pop $R3
  Pop $R2
  Exch $R1
FunctionEnd


# // Get bsp name
# // ===========================
Function GetFirstStrPart
  Exch $R0
  Push $R1
  Push $R2
  StrLen $R1 $R0
  IntOp $R1 $R1 + 1
  loop:
    IntOp $R1 $R1 - 1
    StrCpy $R2 $R0 1 -$R1
    StrCmp $R2 "" exit2
    StrCmp $R2 "|" exit1 ; Change " " to "\" if ur inputting dir path str
  Goto loop
  exit1:
    StrCpy $R0 $R0 -$R1
  exit2:
    Pop $R2
    Pop $R1
    Exch $R0
FunctionEnd


# // Get program command-line params
# // ===========================
Function GetParameters
   Push $R0
   Push $R1
   Push $R2
   StrCpy $R0 $CMDLINE 1
   StrCpy $R1 '"'
   StrCpy $R2 1
   StrCmp $R0 '"' loop
     StrCpy $R1 ' ' ; we're scanning for a space instead of a quote
   loop:
     StrCpy $R0 $CMDLINE 1 $R2
     StrCmp $R0 $R1 loop2
     StrCmp $R0 "" loop2
     IntOp $R2 $R2 + 1
     Goto loop
   loop2:
     IntOp $R2 $R2 + 1
     StrCpy $R0 $CMDLINE 1 $R2
     StrCmp $R0 " " loop2
   StrCpy $R0 $CMDLINE "" $R2
   Pop $R2
   Pop $R1
   Exch $R0
FunctionEnd


# // Random installer left bitmaps
# // ===========================
Function LoadBitmaps
SetDetailsPrint none
Push $R0
Push $R1
Push $R2
GetTempFileName $R0
GetFileTime $R0 $R1 $R2
 StrLen $R1 $R2
 StrCpy $R1 $R2 1 -$R1
  StrCmp $R1 - 0 +5
 StrLen $R1 $R2
 IntOp $R1 $R1 - 1
 StrCpy $R2 $R2 1 -$R1
Goto +2
  StrCpy $R2 $R1
  IntCmp $R2 2 0 0 +3
    SetBrandingImage "$TEMP\ddayupdates\left_logo1.bmp"

Goto set_bitmap_end
  IntCmp $R2 5 0 0 +3
    SetBrandingImage "$TEMP\ddayupdates\left_logo2.bmp"

Goto set_bitmap_end
  IntCmp $R2 7 0 0 +3
    SetBrandingImage "$TEMP\ddayupdates\left_logo3.bmp"

Goto set_bitmap_end
    SetBrandingImage "$TEMP\ddayupdates\left_logo4.bmp"

set_bitmap_end:
Delete $R0
Pop $R2
Pop $R1
Pop $R0
SetDetailsPrint listonly
FunctionEnd


# // Check that bsps exist in maps dir
# // ===========================
Function CheckInstall
Exch $0 ;current loglist
Exch
Exch $1 ;current map list
Push $2 ;universal
Push $3 ;all maps count
Push $4 ;copied maps count
Push $5 ;rest of maps
Push $6 ;maps not found

StrCpy $3 0
StrCpy $4 0
StrCpy $5 $1
StrCpy $6 ""

## Check if 1 or more maps
Push $5
Push ", "
 Call StrStr
Pop $2
StrCmp $2 "" loop

## Change to standard
Push $5
Push ", "
Push "|"
 Call StrReplace
Pop $5

IfFileExists "$EXEDIR\maps" +2
 CreateDirectory "$EXEDIR\maps"

loop:
StrCmp $5 "" loop_exit
Push $5
 Call SplitFirstStrPart1
Pop $2 ;current map
Pop $5 ;rest of maps

 IntOp $3 $3 + 1

## Check for maps
SetDetailsPrint none

IfFileExists "$EXEDIR\$2" 0 +2
 CopyFiles "$EXEDIR\$2" "$EXEDIR\maps\$2"

IfFileExists "$EXEDIR\maps\$2" 0 +3
 IntOp $4 $4 + 1
Goto loop
 StrCpy $6 "$2, $6"
Goto loop

loop_exit:
 StrCpy $6 $6 -2

SetDetailsPrint listonly

StrCmp $4 $3 0 error
DetailPrint "Installation successful [$4/$3 bsps installed]"
StrCpy $0 "$0$\r$\nInstallation was successful [$4/$3 bsps installed]"
StrCpy $1 no

Goto done
error:
DetailPrint "Installation failed"
DetailPrint "Following bsps not installed: $6"
DetailPrint "[$4/$3 bsps installed]"
StrCpy $0 "$0$\r$\nInstallation failed$\r$\nFollowing bsps were not installed: $6$\r$\n[$4/$3 bsps installed]"
StrCpy $1 yes

done:

Sleep 2000

Pop $6
Pop $5
Pop $4
Pop $3
Pop $2
Exch $1 ;fail yes/no
Exch
Exch $0 ;outout loglist
FunctionEnd


# // Create header bitmap
# // ===========================
Function .onGUIInit

## Load logo bitmaps
    SetBrandingImage "$TEMP\ddayupdates\left_logo0.bmp"
    SetBrandingImage /IMGID=1046 "$TEMP\ddayupdates\top_logo.bmp"

FunctionEnd


# // Quit function
# // ===========================
Function Abort

NotifyIcon::Icon r

## Remove old files
Call RemoveFiles

Quit

FunctionEnd


# // Safety remove old files
# // ===========================
Function RemoveFiles

IfFileExists "$TEMP\nst*.tmp" 0 +2
 RMDir /r "$TEMP\nst*.tmp"
IfFileExists "$TEMP\ddayupdates\updates_simple.du" 0 +3
 FlushINI "$TEMP\ddayupdates\updates_simple.du"
 Delete "$TEMP\ddayupdates\updates_simple.du"
IfFileExists "$TEMP\ddayupdates\updates_list.du" 0 +3
 FlushINI "$TEMP\ddayupdates\updates_list.du"
 Delete "$TEMP\ddayupdates\updates_list.du"
IfFileExists "$TEMP\ddayupdates\dialog.du" 0 +3
 FlushINI "$TEMP\ddayupdates\dialog.du"
 Delete "$TEMP\ddayupdates\dialog.du"
IfFileExists "$TEMP\ddayupdates\du_updater.exe" 0 +2
 Delete "$TEMP\ddayupdates\du_updater.exe"
IfFileExists "$TEMP\ddayupdates\listtype.du" 0 +3
 FlushINI "$TEMP\ddayupdates\listtype.du"
 Delete "$TEMP\ddayupdates\listtype.du"
IfFileExists "$TEMP\ddayupdates\objects.du" 0 +3
 FlushINI "$TEMP\ddayupdates\objects.du"
 Delete "$TEMP\ddayupdates\objects.du"
IfFileExists "$TEMP\ddayupdates\du_listtype.exe" 0 +2
 Delete "$TEMP\ddayupdates\du_listtype.exe"

FunctionEnd


# // Safety remove old files
# // ===========================
Function .onUserAbort

NotifyIcon::Icon r

SetDetailsPrint none

## Remove old files
Call RemoveFiles

SetDetailsPrint listonly

FunctionEnd


# // Safety remove old files
# // ===========================
Function .onInstSuccess

NotifyIcon::Icon r

SetDetailsPrint none

## Remove old files
Call RemoveFiles

SetDetailsPrint listonly

FunctionEnd


# // Init
# // ===========================
Function .onInit

BringToFront

## Check that the program is within the D-Day: Normandy game directory
Push "$EXEDIR"
Push "dday\dday"
 Call StrStr
Pop $R0
StrCmp $R0 "" 0 directory_ok

Push "$EXEDIR"
Push "q2demo\dday"
 Call StrStr
Pop $R0
StrCmp $R0 "" 0 directory_ok

Push "$EXEDIR"
Push "quake2\dday"
 Call StrStr
Pop $R0
StrCmp $R0 "" 0 directory_ok

Push "$EXEDIR"
Push "quake"
 Call StrStr
Pop $R0
StrCmp $R0 "" directory_notok

Push "$EXEDIR"
Push "\dday"
 Call StrStr
Pop $R0
StrCmp $R0 "" directory_notok directory_ok

## Report that app is in wrong dir and quit
directory_notok:
MessageBox MB_OK|MB_ICONEXCLAMATION "${ERROR_MSG7}" IDCANCEL +2
Call Abort
directory_ok:

#########################################################################################################################################
## Uninstall area
####################################
Call GetParameters
 Pop $R0
StrCmp $R0 "-uninstall" 0 no_uninstall

 MessageBox MB_YESNOCANCEL|MB_ICONQUESTION "D-Day Updater will now be uninstalled from your system.$\r$\nAre you sure you wish to continue?" IDYES uninstall IDNO no_uninstall
u_abort:
  Call Abort

uninstall:
 MessageBox MB_YESNOCANCEL|MB_ICONQUESTION "Remove D-Day Updater system files?" IDNO skip_u1 IDCANCEL u_abort

RMDir /r "$TEMP\ddayupdates"
Sleep 2000
skip_u1:

 MessageBox MB_YESNOCANCEL|MB_ICONQUESTION "Delete D-Day Updater registry entries?" IDNO skip_u2 IDCANCEL u_abort

DeleteRegKey HKLM "SOFTWARE\D-Day Updater"
Sleep 2000
skip_u2:

 MessageBox MB_OK|MB_ICONINFORMATION "Uninstallation was successful."
  Call Abort
no_uninstall:
####################################
## Uninstall area END
#########################################################################################################################################

Banner::show /NOUNLOAD /set 76 "D-Day Updater is loading," "please wait..."

####################################
## TEMP remove old files
####################################
IfFileExists "$TEMP\ddayupdates\*.txt" +3
IfFileExists "$TEMP\ddayupdates\*.ini" +2
IfFileExists "$TEMP\ddayupdates\*.url" 0 +3
 MessageBox MB_OK|MB_ICONINFORMATION "D-Day Updater detected old un-needed files.$\r$\nThey will be removed."
 Delete "$TEMP\ddayupdates\*.*"

## Create dump directory
IfFileExists "$TEMP\ddayupdates" +2
 CreateDirectory "$TEMP\ddayupdates"

## Remove old files
Call RemoveFiles

## Download vital file
objects_top:
!insertmacro URLS_START
Push ${OBJECTS_URL1}
Push ${OBJECTS_URL2}
!insertmacro URLS_END
!insertmacro NSISdl "" "silent" "$TEMP\ddayupdates" "objects.du"
 Pop $R0
Banner::destroy
 StrCmp $R0 success objects_ok
 MessageBox MB_RETRYCANCEL|MB_ICONSTOP "${ERROR_MSG8}" IDRETRY objects_top
  Call Abort
objects_ok:

Banner::show /NOUNLOAD /set 76 "D-Day Updater is loading," "please wait..."

#########################################################################################################################################
## D-Day Updater Self-Updater code
####################################
ReadINIStr $R0 "$TEMP\ddayupdates\settings.du" "Field 4" "State"
 StrCmp $R0 0 skip_versioncheck

## Read from update version file then compare with current date
 ReadINIStr $R0 "$TEMP\ddayupdates\objects.du" "D-Day Updater Version" "Date"
  StrCmp $R0 "${DATE}" skip_versioncheck

Banner::destroy
 MessageBox MB_YESNOCANCEL|MB_ICONQUESTION "${MISC_MSG2}" IDNO skip_versioncheck IDYES +2
  Call Abort

## Download new D-Day Updater app (if "$R3.$R2" is different to "${VERSION}")
retry_download:
Banner::show /NOUNLOAD /set 76 "Downloading update, please wait..." ""
!insertmacro URLS_START
Push ${UPDATE_FILE_URL1}
Push ${UPDATE_FILE_URL2}
!insertmacro URLS_END
  !insertmacro NSISdl "" "silent" "$TEMP\ddayupdates" "ddayupdater.exe"
  Pop $R0
Banner::destroy
  StrCmp $R0 success noprob
 MessageBox MB_YESNO|MB_ICONEXCLAMATION "${ERROR_MSG4}" IDYES retry_download IDNO skip_versioncheck
noprob:

## Write stuff for du_updater.exe
 ReadINIStr $R0 "$TEMP\ddayupdates\objects.du" "D-Day Updater Version" "Date"
 WriteRegStr HKLM "SOFTWARE\D-Day Updater" "MODDATE" "$R0"
 ReadINIStr $R0 "$TEMP\ddayupdates\objects.du" "D-Day Updater Version" "CurrentVersion"
 ReadINIStr $R1 "$TEMP\ddayupdates\objects.du" "D-Day Updater Version" "CurrentBeta"
 WriteRegStr HKLM "SOFTWARE\D-Day Updater" "VERSION1" "$R0$R1"
 WriteRegStr HKLM "SOFTWARE\D-Day Updater" "VERSION2" "${VERSION}${BETA}"
 WriteRegStr HKLM "SOFTWARE\D-Day Updater" "EXEDIR"   "$EXEDIR"

## Extract + run du_updater.exe
File "/oname=$TEMP\ddayupdates\du_updater.exe" "du_updater.exe"
Exec "$TEMP\ddayupdates\du_updater.exe"
Call Abort

skip_versioncheck:
####################################
## D-Day Updater Self-Updater code END
#########################################################################################################################################

## Extract logo bitmaps
    File "/oname=$TEMP\ddayupdates\top_logo.bmp"   "${BITMAP_TOP}"
    File "/oname=$TEMP\ddayupdates\left_logo0.bmp" "${BITMAP_LEFT0}"
    File "/oname=$TEMP\ddayupdates\left_logo1.bmp" "${BITMAP_LEFT1}"
    File "/oname=$TEMP\ddayupdates\left_logo2.bmp" "${BITMAP_LEFT2}"
    File "/oname=$TEMP\ddayupdates\left_logo3.bmp" "${BITMAP_LEFT3}"
    File "/oname=$TEMP\ddayupdates\left_logo4.bmp" "${BITMAP_LEFT4}"
    File "/oname=$TEMP\ddayupdates\logo_48x.bmp"   "design\logo_48x.bmp"
    File "/oname=$TEMP\ddayupdates\load_bg.bmp"    "design\load_bg.bmp"

## Extract misc files
    File "/oname=$TEMP\ddayupdates\settings.dll"    "${NSISDIR}\Plugins\nsisdt.dll"
    File "/oname=$TEMP\ddayupdates\dialog.du"       "dialog.ini"
    File "/oname=$TEMP\ddayupdates\du_listtype.exe" "du_listtype.exe"

## Check OS for correct dialog
ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion" ProductName
StrCmp $R0 "" 0 +2
ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows NT\CurrentVersion" ProductName

Push $R0
Push 2000
 Call StrStr
Pop $R1
StrCmp $R1 "" 0 extract_xp
Push $R0
Push xp
 Call StrStr
Pop $R1
StrCmp $R1 "" extract_9x
extract_xp:
File "/oname=$TEMP\ddayupdates\ddma.bmp" "ddma.bmp"
Goto extract_out
extract_9x:
File "/oname=$TEMP\ddayupdates\ddma.bmp" "ddma2.bmp"
extract_out:

## Set ddma bitmap
WriteINIStr "$TEMP\ddayupdates\dialog.du" "Field 4" "Text" "$TEMP\ddayupdates\ddma.bmp"

## Ask which downloads to list
Banner::destroy

ExecWait "$TEMP\ddayupdates\du_listtype.exe"

ReadRegStr $0 HKLM "SOFTWARE\D-Day Updater" "ABORT"
 StrCmp $0 1 0 noquit
Call Abort
noquit:

## Get which downloads to list
ReadRegStr $0 HKLM "SOFTWARE\D-Day Updater" "LISTTYPE"

## Write filter modes to dialog.du
StrCmp $0 Rec 0 +2
WriteINIStr "$TEMP\ddayupdates\dialog.du" "Field 7" "Text" "Map Filter: Recommended"
StrCmp $0 NonRec 0 +2
WriteINIStr "$TEMP\ddayupdates\dialog.du" "Field 7" "Text" "Map Filter: Unrecommended"
StrCmp $0 All 0 +2
WriteINIStr "$TEMP\ddayupdates\dialog.du" "Field 7" "Text" "Map Filter: None"

IfFileExists "$TEMP\ddayupdates\objects.du" listok

MessageBox MB_OKCANCEL|MB_ICONEXCLAMATION "${ERROR_MSG3}" IDOK +2
Call Abort
 StrCpy $0 All
listok:

Banner::show /NOUNLOAD /set 76 "D-Day Updater is loading," "please wait..."

## Download updates list
retry:
NSISdl::download_quiet "${MAP_LIST_URL}" "$TEMP\ddayupdates\updates.du"
 Pop $R0
  StrCmp $R0 success downloadok

## Report if not connected to the net
Banner::destroy
MessageBox MB_ABORTRETRYIGNORE|MB_ICONEXCLAMATION "${ERROR_MSG6}" IDRETRY retry IDIGNORE skipabort
Call Abort
skipabort:

Banner::show /NOUNLOAD /set 76 "D-Day Updater is loading," "please wait..."

## If old updates list still exists, then bad!
IfFileExists "$TEMP\ddayupdates\updates.du" +4
WriteINIStr "$TEMP\ddayupdates\dialog.du" "Field 5" "State" "${ERROR_MSG2}"
WriteINIStr "$TEMP\ddayupdates\dialog.du" "Field 3" "Type"  "Text"
WriteINIStr "$TEMP\ddayupdates\dialog.du" "Field 3" "Flags" "MULTILINE|VSCROLL|DISABLED"

## Check for manually downloaded updates file
IfFileExists "$EXEDIR\updates.txt" 0 +3
Rename "$EXEDIR\updates.txt" "$TEMP\ddayupdates\updates.du"
Goto downloadok

## No updates list found
WriteINIStr "$TEMP\ddayupdates\dialog.du" "Field 5" "State" "${ERROR_MSG1}"

downloadok:

## Extract new dialog for du_settings.exe
IfFileExists "$TEMP\ddayupdates\settings.du" 0 extract_settings
ReadINIStr $R0 "$TEMP\ddayupdates\settings.du" "File Version" "Value"

 StrCmp $R0 ${DIALOG_VERSION} no_extract_settings

extract_settings:
File "/oname=$TEMP\ddayupdates\settings.du" "settings.ini"
File "/oname=$TEMP\ddayupdates\set_bg.bmp"   "design\set_bg.bmp"
no_extract_settings:

WriteINIStr "$TEMP\ddayupdates\settings.du" "Field 1" "Text" "$TEMP\ddayupdates\logo_48x.bmp"
WriteINIStr "$TEMP\ddayupdates\settings.du" "Field 15" "Text" "$TEMP\ddayupdates\set_bg.bmp"

## Extract du_settings.exe
File "/oname=$TEMP\ddayupdates\du_settings.exe" "du_settings.exe"

IfFileExists "$TEMP\ddayupdates\updates.du" 0 stats_exit

StrCpy ${BSPS} 0
StrCpy ${ZIPS} 0
StrCpy ${ALLBSPS} 0
StrCpy ${ALLZIPS} 0

StrCpy $R1 0
StrCpy $R2 ""
StrCpy $R5 ""

loop_maplist:

IntOp $R1 $R1 + 1
ReadINIStr $R0 "$TEMP\ddayupdates\updates.du" "Maps" "$R1" #get map info from list
 StrCmp $R0 "" exit_maplist

## Get map bsp name
Push $R0
 Call GetFirstStrPart
Pop $R3

## Get map zip name
Push 4
Push 1
Push $R0
 Call AdvStrSort
Pop $R0

## Add to all archive ZIPS count
StrCmp $R0 $R5 +3
IntOp ${ALLZIPS} ${ALLZIPS} + 1
StrCpy $R5 $R0

####################################
## Check if download bsp is installed or not
#########################################################################################################################################
IfFileExists "$EXEDIR\maps\$R3" 0 +5

ReadINIStr $1 "$TEMP\ddayupdates\objects.du" "New map versions" "$R3"
 StrCmp $1 "" loop_maplist

ReadINIStr $2 "$TEMP\ddayupdates\objects.du" "New map versions" "$R3-zip"
 StrCmp $2 $R0 0 loop_maplist

 Push "$EXEDIR\maps\$R3"
 Call FileSizeNew
 Pop $2
 StrCmp $1 $2 loop_maplist

## Check if recommended download
StrCmp $0 NonRec 0 list1
 ReadINIStr $1 "$TEMP\ddayupdates\objects.du" "Good maps" "$R3"
  StrCmp $1 "" list2 loop_maplist
list1:

StrCmp $0 All list2
 ReadINIStr $1 "$TEMP\ddayupdates\objects.du" "Good maps" "$R3"
  StrCmp $1 1 list2 loop_maplist
list2:

## Add to BSPS count
IntOp ${BSPS} ${BSPS} + 1

## Log map info
read:
IntOp $R4 $R4 + 1
ReadINIStr $R3 "$TEMP\ddayupdates\updates_simple.du" "Maps" "$R0_$R4"
StrCmp $R3 "" 0 read

WriteINIStr "$TEMP\ddayupdates\updates_simple.du" "Maps" "$R0_$R4" "$R1" #write to another list for later use
StrCpy $R4 0

## Add all map zips to list
ReadINIStr $R3 "$TEMP\ddayupdates\updates_list.du" "Maps" "$R0"
StrCmp $R3 Map loop_maplist

StrCpy $R2 "$R2$R0|"
WriteINIStr "$TEMP\ddayupdates\updates_list.du" "Maps" "$R0" "Map"

## Add to ZIPS count
IntOp ${ZIPS} ${ZIPS} + 1

Goto loop_maplist

## All archive BSPS count
exit_maplist:
IntOp $R1 $R1 - 1
StrCpy ${ALLBSPS} $R1

## Remove last pipeline character
StrCpy $R2 $R2 -1

##################################################################
## Write all detected maps
##################################################################
WriteINIStr "$TEMP\ddayupdates\dialog.du" "Field 3" "ListItems" "$R2"

## Write environment stuff to settings dialog
WriteINIStr "$TEMP\ddayupdates\settings.du" "Settings" "Title" "${NAME} - Program Settings"
WriteINIStr "$TEMP\ddayupdates\settings.du" "Field 2" "State" "$EXEDIR"
WriteINIStr "$TEMP\ddayupdates\dialog.du" "Field 6" "State" "${WEBSITE_URL}"

ReadINIStr $R0 "$TEMP\ddayupdates\settings.du" "Field 3" "State"
 StrCmp $R0 "" 0 +2
WriteINIStr "$TEMP\ddayupdates\settings.du" "Field 3" "State" "$EXEDIR\ddayupdates"

## Download stats
WriteINIStr "$TEMP\ddayupdates\dialog.du" "Field 5" "State" "Total Downloads: \
[${BSPS}/${ALLBSPS} bsps in ${ZIPS}/${ALLZIPS} zips] \
:${ZIPS} is a lot of downloads to get!"

IntCmp ${BSPS} 100 0 +3 0
WriteINIStr "$TEMP\ddayupdates\dialog.du" "Field 5" "State" "Total Downloads: \
[${BSPS}/${ALLBSPS} bsps in ${ZIPS}/${ALLZIPS} zips] \
:You have a lot of work to do!"
Goto stats_exit

IntCmp ${BSPS} 80 0 +3 0
WriteINIStr "$TEMP\ddayupdates\dialog.du" "Field 5" "State" "Total Downloads: \
[${BSPS}/${ALLBSPS} bsps in ${ZIPS}/${ALLZIPS} zips] \
:Hurry up and get those maps!"
Goto stats_exit

IntCmp ${BSPS} 60 0 +3 0
WriteINIStr "$TEMP\ddayupdates\dialog.du" "Field 5" "State" "Total Downloads: \
[${BSPS}/${ALLBSPS} bsps in ${ZIPS}/${ALLZIPS} zips] \
:Still have ${ZIPS} more zips to get!"
Goto stats_exit

IntCmp ${BSPS} 40 0 +3 0
WriteINIStr "$TEMP\ddayupdates\dialog.du" "Field 5" "State" "Total Downloads: \
[${BSPS}/${ALLBSPS} bsps in ${ZIPS}/${ALLZIPS} zips] \
:Still ${ZIPS} more zips to download!"
Goto stats_exit

IntCmp ${BSPS} 20 0 +3 0
WriteINIStr "$TEMP\ddayupdates\dialog.du" "Field 5" "State" "Total Downloads: \
[${BSPS}/${ALLBSPS} bsps in ${ZIPS}/${ALLZIPS} zips] \
:Keeping reasonably up-to-date!"
Goto stats_exit

IntCmp ${BSPS} 10 0 +3 0
WriteINIStr "$TEMP\ddayupdates\dialog.du" "Field 5" "State" "Total Downloads: \
[${BSPS}/${ALLBSPS} bsps in ${ZIPS}/${ALLZIPS} zips] \
:${ZIPS} more zips to download!"
Goto stats_exit

IntCmp ${BSPS} 5 0 0 stats_exit
WriteINIStr "$TEMP\ddayupdates\dialog.du" "Field 5" "State" "Total Downloads: \
[${BSPS}/${ALLBSPS} bsps in ${ZIPS}/${ALLZIPS} zips] \
:Nice, only ${ZIPS} zips to get!"
Goto +4

StrCmp ${BSPS} 1 0 +3
WriteINIStr "$TEMP\ddayupdates\dialog.du" "Field 5" "State" "Total Downloads: \
[${BSPS}/${ALLBSPS} bsps in ${ZIPS}/${ALLZIPS} zips] \
:Great! Only 1 zip to download!"
Goto stats_exit

StrCmp ${BSPS} 0 0 stats_exit
WriteINIStr "$TEMP\ddayupdates\dialog.du" "Field 5" "State" "${MISC_MSG1}"
WriteINIStr "$TEMP\ddayupdates\dialog.du" "Field 3" "Type"  "Text"
WriteINIStr "$TEMP\ddayupdates\dialog.du" "Field 3" "Flags" "MULTILINE|VSCROLL|DISABLED"

stats_exit:

Banner::destroy

FunctionEnd


# // Open settings dialog
# // ===========================
Function Settings

Abort

FunctionEnd


# // Select map dialog
# // ===========================
Function MainDialog

## Add System Tray icon
NotifyIcon::Icon /NOUNLOAD yit 103 "D-Day Updater ${VERSION}${BETA}"

## Add header text and colour
!insertmacro HEADER_TEXT "Detected Updates" "Updates that have not yet been installed"

## Show dialog
pagetop:
 InstallOptions::dialog "$TEMP\ddayupdates\dialog.du"
 Pop $R0
 StrCmp $R0 back settings
 StrCmp $R0 cancel pagecancel
 StrCmp $R0 success pagesuccess
 StrCmp $R0 error pagecancel

## Open settings dialog
settings:
ExecWait "$TEMP\ddayupdates\du_settings.exe"
Goto pagetop

## Go
pagesuccess:
ReadINIStr $R0 "$TEMP\ddayupdates\dialog.du" "Field 3" "Type"
StrCmp $R0 "Text" 0 pagecancel

ReadINIStr $R0 "$TEMP\ddayupdates\dialog.du" "Field 5" "State"
StrCmp $R0 "${ERROR_MSG2}" +2

MessageBox MB_OK|MB_ICONEXCLAMATION "There are no new detected updates.$\r$\nYou are up-to-date!" IDOK pagetop
MessageBox MB_OK|MB_ICONEXCLAMATION "There was no updates list found!$\r$\nYou cannot continue." IDOK pagetop

## Close
pagecancel:

FunctionEnd


# // Downloading
# // ===========================
Section ""

WriteRegStr HKLM "SOFTWARE\D-Day Updater" "SETTINGS" "0"

## Change Close button to Cancel button
GetDlgItem $R0 $HWNDPARENT 2
SendMessage $R0 ${WM_SETTEXT} 0 "STR:Cancel"

## Add header text and colour
!insertmacro HEADER_TEXT "Downloading Updates" ""

## Tells only to list items in window
SetDetailsPrint listonly

## Get list of selected items
ReadINIStr $R0 "$TEMP\ddayupdates\dialog.du" "Field 3" "State"

## User wants to download all (none selected = download all)
StrCmp $R0 "" 0 +2
ReadINIStr $R0 "$TEMP\ddayupdates\dialog.du" "Field 3" "ListItems"

## No updates list found
ReadINIStr $R1 "$TEMP\ddayupdates\dialog.du" "Field 5" "State"
 StrCmp $R1 "${ERROR_MSG1}" 0 no_error

DetailPrint "========================================="
DetailPrint "${ERROR_MSG1}"
DetailPrint "Read program tips in the D-Day Updater readme for more information."
DetailPrint "The readme file can be opened from the D-Day Updater settings tab."
DetailPrint "========================================="
Goto download_done
no_error:

## Old updates list found
ReadINIStr $R1 "$TEMP\ddayupdates\dialog.du" "Field 5" "State"
 StrCmp $R1 "${ERROR_MSG2}" 0 download_loop

DetailPrint "========================================="
DetailPrint "${ERROR_MSG2}"
DetailPrint "The current updates are taken from an old updates list."
DetailPrint "These updates may no longer be on the server, and the download"
DetailPrint "urls could be invalid."
DetailPrint "========================================="

StrCpy ${ALLZIPS} ${ZIPS}
StrCpy ${FAILS}   0
StrCpy ${CANCELS} 0

Push $R0
 Call ItemCount
Pop ${ZIPS}
IntOp ${ZIPS} ${ZIPS} + 1

download_loop:

## Add random bitmaps to left
Call LoadBitmaps

## Start log string (starts with date)
ReadINIStr $R6 "$TEMP\ddayupdates\settings.du" "Field 11" "State"
StrCmp $R6 0 nodate
 Push $0
 StrCpy $0 "%c"
 CallInstDLL "$TEMP\ddayupdates\settings.dll" currentdate

 StrCpy $R6 "$\r$\n$0$\r$\n========================================="
 Pop $0
nodate:

## Get hold of next zip name and remove "[zipname]|" from start of selected items
StrCmp $R0 "" download_done
Push $R0
 Call SplitFirstStrPart1
Pop $R1
Pop $R0

## Read different download items
ReadINIStr $R2 "$TEMP\ddayupdates\updates_simple.du" "Maps" "$R1_1"
StrCmp $R2 "" 0 +6
DetailPrint "========================================="
DetailPrint "Invalid download file: $R1"
DetailPrint "========================================="
Sleep 1000
Goto download_loop

## Goto last ini entry
StrCpy $R4 1
StrCpy $R5 ""
read_loop:
ReadINIStr $R2 "$TEMP\ddayupdates\updates_simple.du" "Maps" "$R1_$R4"
StrCmp $R2 "" read_exit
ReadINIStr $R2 "$TEMP\ddayupdates\updates.du" "Maps" "$R2"

## Get map bsp name
Push $R2
 Call GetFirstStrPart
Pop $R3

## Add to list of bsp names in zip (campaigns)
StrCpy $R5 "$R5$R3, "
IntOp $R4 $R4 + 1

Goto read_loop
read_exit:

## Remove old log stuff
ReadINIStr $R4 "$TEMP\ddayupdates\settings.du" "Field 12" "State"
StrCmp $R4 0 no_remove_log
 Call ClearDetails
no_remove_log:

DetailPrint "========================================="

## Show current download
ReadRegStr $R2 HKLM "SOFTWARE\D-Day Updater" "COUNTCURRENT"
 StrCmp $R2 start 0 +2
  StrCpy $R2 0

IntOp $R2 $R2 + 1

DetailPrint "Selected items ${ZIPS} out of ${ALLZIPS}"

DetailPrint "Download $R2 of ${ZIPS}"

Push $R2 #store

StrCmp $R6 0 +2 # Add to log
 StrCpy $R6 "Download $R2 of ${ZIPS}"

WriteRegStr HKLM "SOFTWARE\D-Day Updater" "COUNTCURRENT" "$R2"

## Get download number
ReadRegStr $R2 HKLM "SOFTWARE\D-Day Updater" "COUNT"
 StrCmp $R2 "" 0 notzero1

Push $0
 StrCpy $0 "%c"
 CallInstDLL "$TEMP\ddayupdates\settings.dll" currentdate

WriteRegStr HKLM "SOFTWARE\D-Day Updater" "DATE" "$0"
Pop $0

StrCpy $R2 0
WriteRegStr HKLM "SOFTWARE\D-Day Updater" "COUNT" "$R2"
notzero1:

ReadRegStr $R3 HKLM "SOFTWARE\D-Day Updater" "DATE"
IntOp $R2 $R2 + 1

DetailPrint "Download number: $R2 since $R3"

StrCmp $R6 0 +2 # Add to log
 StrCpy $R6 "Download number: $R2 since $R3"

WriteRegStr HKLM "SOFTWARE\D-Day Updater" "COUNT" "$R2"

## Get zip archive number
ReadINIStr $R2 "$TEMP\ddayupdates\updates_simple.du" "Maps" "$R1_1"

## DDMA zip archive number
StrCmp $R6 0 +2 # Add to log
 StrCpy $R6 "$R6$\r$\nMap archive number: $R2"
DetailPrint "Map archive number: $R2"

## Get zip archive string
ReadINIStr $R2 "$TEMP\ddayupdates\updates.du" "Maps" "$R2"

## Get map zip name
Push 4
Push 1
Push $R2
 Call AdvStrSort
Pop $R4

StrCmp $R6 0 +2 # Add to log
 StrCpy $R6 "$R6$\r$\nDownload name: $R4"
DetailPrint "Download name: $R4"

Pop $R2 #return

NotifyIcon::Icon /NOUNLOAD myitn 103 "D-Day Updater ${VERSION}${BETA}" "Downloading..." "$R4 ($R2/${ZIPS})"

Push $R4 #save value

## Add header text and colour
!insertmacro HEADER_TEXT "Downloading Updates" "Download: $R4"

## Get map author
Push 1
Push 1
Push $R2
 Call AdvStrSort
Pop $R3

 Push $R3
 Push "${MISC_MSG3}"
  Call StrStr
 Pop $R4
 StrCmp $R4 "" +2
 StrCpy $R3 "(Unknown)"

## Check if map is single or a campaign
StrCpy $R5 $R5 -2
StrCpy ${MAPLIST} $R5 ##Store variable

## Single map or campaign?
Push $R5
Push ","
 Call StrStr
Pop $R4
StrCmp $R4 "" 0 maps_multiple

## Map and map author for the single map
StrCmp $R6 0 +2 # Add to log
 StrCpy $R6 "$R6$\r$\nMap: $R5$\r$\nMap by: $R3"
DetailPrint "Map: $R5"
DetailPrint "Map by: $R3"
Goto maps_exit

## Map and map author for the campaign
maps_multiple:
StrCmp $R6 0 +2 # Add to log
 StrCpy $R6 "$R6$\r$\nMaps: $R5$\r$\nMaps by: $R3"
DetailPrint "Maps: $R5"
DetailPrint "Maps by: $R3"
maps_exit:

## Get map info
Push 2
Push 1
Push $R2
 Call AdvStrSort
Pop $R3

StrCmp $R6 0 +2 # Add to log
 StrCpy $R6 "$R6$\r$\nInfo: $R3"
DetailPrint "Info: $R3"

## Get urls
Push 3
Push 1
Push $R2
 Call AdvStrSort
Pop $R3

Push $R3
 Call SplitFirstStrPart2
Pop $R7 ;map mirror url
Pop $R5 ;map site url

## If download manual is on
ReadINIStr $R3 "$TEMP\ddayupdates\settings.du" "Field 8" "State"
 StrCmp $R3 1 0 download_external

## Download zip
Sleep 2000
Pop $R4 #get value back
 SetDetailsPrint none
ReadINIStr $R5 "$TEMP\ddayupdates\settings.du" "Field 3" "State"

IfFileExists $R5 +2
 CreateDirectory $R5


IfFileExists "$R5\$R4" 0 +3
 MessageBox MB_YESNO|MB_ICONINFORMATION "The download item $R4 is already in $R5.$\r$\nWould you like to download it again?" IDNO installzip

Rename "$R5\$R4" "$R5\$R4.old"

NSISdl::download "$R7" "$R5\$R4"
 SetDetailsPrint listonly
  Pop $R3
  StrCmp $R3 cancel 0 noabort

## User cancelled download
StrCmp $R0 "" last_cancelled
MessageBox MB_YESNO|MB_ICONQUESTION "Cancel all other downloads aswell?$\r$\n(You can download them later.)" IDYES all_cancelled

## User cancelled just that download
StrCmp $R6 0 +2 # Add to log
 StrCpy $R6 "$R6$\r$\nDownload cancelled"
DetailPrint "Download cancelled"
IntOp ${CANCELS} ${CANCELS} + 1

IfFileExists "$R5\$R4.old" 0 writetolog
Rename "$R5\$R4.old" "$R5\$R4"
Goto writetolog

## User cancelled all other downloads aswell
all_cancelled:
StrCmp $R6 0 +2 # Add to log
 StrCpy $R6 "$R6$\r$\nDownload cancelled"
DetailPrint "All downloads cancelled"
StrCpy ${CANCELS} ${ZIPS}

IfFileExists "$R5\$R4.old" 0 writetolog2
Rename "$R5\$R4.old" "$R5\$R4"
Goto writetolog2

## User cancelled last download
last_cancelled:
StrCmp $R6 0 +2 # Add to log
 StrCpy $R6 "$R6$\r$\nDownload cancelled"
DetailPrint "Download cancelled"
IntOp ${CANCELS} ${CANCELS} + 1

IfFileExists "$R5\$R4.old" 0 writetolog2
Rename "$R5\$R4.old" "$R5\$R4"
Goto writetolog2

## Download was successful
noabort:
  StrCmp $R3 error 0 +3
DetailPrint "Error occurred during downloading"
DetailPrint "Please contact Afrow UK if problem persists"
  StrCmp $R3 success 0 failed
DetailPrint "Download successful"

StrCmp $R6 0 installzip # Add to log
 StrCpy $R6 "$R6$\r$\nDownload successful"

IfFileExists "$R5\$R4.old" 0 installzip
Delete "$R5\$R4.old"
Goto installzip

## Download failed (not cancelled)
failed:
StrCmp $R6 0 download_loop # Add to log
 StrCpy $R6 "$R6$\r$\nDownload failed"
Goto writetolog

DetailPrint "Download failed"
DetailPrint "Attempt to download later or try downloading manually"

## Install zip
installzip:
ReadINIStr $R3 "$TEMP\ddayupdates\settings.du" "Field 5" "State"
 StrCmp $R3 0 noinstall

DetailPrint "Installing $R4 to $EXEDIR"

 SetDetailsPrint none
ReadINIStr $R5 "$TEMP\ddayupdates\settings.du" "Field 3" "State"
IfFileExists "$R5\7za.exe" noextract7za
File "/oname=$R5\7za.exe" "7za.exe"
noextract7za:
Sleep 1000
NotifyIcon::Icon /NOUNLOAD myitn 103 "D-Day Updater ${VERSION}${BETA}" "Installing..." "$R4"
SetOutPath $R5
nsExec::Exec "$\"$R5\7za.exe$\" x $\"$R4$\" -aoa $\"-o$EXEDIR$\""
 SetDetailsPrint listonly

## Check install was successful
Push ${MAPLIST} ##list of maps
Push $R6 ##loglist
Call CheckInstall
Pop $R6 ##output loglist
Pop $R4 ##failed yes/no

StrCmp $R4 yes writetolog
IntOp ${FAILS} ${FAILS} + 1

Goto writetolog
noinstall:

## Download manual
download_external:
 SetDetailsPrint none
ExecShell open $R5
 SetDetailsPrint listonly

## Write to log
writetolog:
StrCmp $R6 0 download_loop
 StrCpy $R6 "$R6$\r$\n========================================="
 Push $R6
 Push "$EXEDIR\du_downloads.txt"
  Call WriteToFile
DetailPrint "Download info logged ($EXEDIR\du_downloads.txt)"

# Pause prompt
ReadINIStr $R3 "$TEMP\ddayupdates\settings.du" "Field 7" "State"
 StrCmp $R3 0 nopause
StrCmp $R0 "" 0 +2
MessageBox MB_OK|MB_ICONINFORMATION "Click OK to finish...$\r$\n$\r$\n(You can disable this via the Program Settings tab)" IDOK download_done
MessageBox MB_OKCANCEL|MB_ICONINFORMATION "Click OK to download the next file...$\r$\n$\r$\n(You can disable this via the Program Settings tab)" IDCANCEL download_done
Goto download_loop
nopause:

Sleep 1000

Goto download_loop
## Write to log 2
writetolog2:
StrCmp $R6 0 download_loop
 StrCpy $R6 "$R6$\r$\n========================================="
 Push $R6
 Push "$EXEDIR\du_downloads.txt"
  Call WriteToFile
DetailPrint "Download info logged ($EXEDIR\du_downloads.txt)"

download_done:

ReadINIStr $R5 "$TEMP\ddayupdates\settings.du" "Field 3" "State"
 SetDetailsPrint none
IfFileExists "$R5\7za.exe" 0 +2
 Delete "$R5\7za.exe"
 SetDetailsPrint listonly

WriteRegStr HKLM "SOFTWARE\D-Day Updater" "COUNTCURRENT" "start"

DetailPrint "========================================="

## Show install stats
ReadINIStr $R3 "$TEMP\ddayupdates\settings.du" "Field 5" "State"
 StrCmp $R3 0 noinstallmsg
StrCmp ${FAILS} 0 installmsgfail

NotifyIcon::Icon /NOUNLOAD myitn 103 "D-Day Updater ${VERSION}${BETA}" "Completed" "All downloads installed"
DetailPrint "All downloads installed"
Goto noinstallmsg2

installmsgfail:
NotifyIcon::Icon /NOUNLOAD myitn 103 "D-Day Updater ${VERSION}${BETA}" "Completed" "${FAILS}/${ZIPS} download installations failed"
DetailPrint "${FAILS}/${ZIPS} download installs failed"
Goto noinstallmsg2

noinstallmsg:
StrCmp ${CANCELS} 0 noinstallmsg2x
NotifyIcon::Icon /NOUNLOAD myitn 103 "D-Day Updater ${VERSION}${BETA}" "Completed" "(${CANCELS}/${ZIPS} downloads cancelled)"
Goto noinstallmsg2
noinstallmsg2x:
NotifyIcon::Icon /NOUNLOAD myitn 103 "D-Day Updater ${VERSION}${BETA}" "Completed" ""
noinstallmsg2:

Sleep 1000

## Add header text and colour
!insertmacro HEADER_TEXT "Completed" ""

## Re-launch program
 SetDetailsPrint none
ReadINIStr $R3 "$TEMP\ddayupdates\settings.du" "Field 6" "State"
 StrCmp $R3 0 nolaunch
Exec "$EXEDIR\ddayupdater.exe"
Call Abort
nolaunch:
 SetDetailsPrint listonly

SectionEnd
