;  This file is part of Warzone 2100.
;  Copyright (C) 2006-2018  Warzone 2100 Project
;  Copyright (C) 2006       Dennis Schridde
;
;  Warzone 2100 is free software; you can redistribute it and/or modify
;  it under the terms of the GNU General Public License as published by
;  the Free Software Foundation; either version 2 of the License, or
;  (at your option) any later version.
;
;  Warzone 2100 is distributed in the hope that it will be useful,
;  but WITHOUT ANY WARRANTY; without even the implied warranty of
;  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;  GNU General Public License for more details.
;
;  You should have received a copy of the GNU General Public License
;  along with Warzone 2100; if not, write to the Free Software
;  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
;
;  NSIS Modern User Interface
;  Warzone 2100 Project Installer script
;

; IMPORTANT: This installer script should be compiled with NSIS 3.0+.
;            Because source-builds of NSIS may not define NSIS_PACKEDVERSION
;            it is not explicitly checked here.

;Create a Unicode installer (must come first)
Unicode true

;--------------------------------
;Include section

  !include "MUI.nsh"
  !include "FileFunc.nsh"
  !include "LogicLib.nsh"
  !include "x64.nsh"

  !include "..\..\..\NSIS.definitions.nsh"
  !include "${TOP_BUILDDIR}\NSIS.version.nsh"

  !include "${TOP_SRCDIR}\pkg\nsis\stringhelpers.nsh"

;--------------------------------
;Required plugins

  !define ADDITIONAL_PLUGINS_DIR "${TOP_SRCDIR}\pkg\nsis\plugins"

  !addplugindir /x86-ansi "${ADDITIONAL_PLUGINS_DIR}\x86-ansi"
  !addplugindir /x86-unicode "${ADDITIONAL_PLUGINS_DIR}\x86-unicode"

;--------------------------------
;General
  CRCCheck on  ;make sure this isn't corrupted

  ;Name and file
  Name "${PACKAGE_NAME}"
  OutFile "@CPACK_TOPLEVEL_DIRECTORY@/@CPACK_OUTPUT_FILE_NAME@"

  ;Set compression
  SetCompressor @CPACK_NSIS_COMPRESSOR@

  ;Ensure that the installer is explicitly marked as supporting Win7 through Win10
  ;to ensure Windows version checks return the true value
  ManifestSupportedOS Win7 Win8 Win8.1 {8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}

  ;Enable high-DPI support for the installer
  ;NOTE: The only quirk detected is with the checkbox bitmap used for the tree control (which doesn't scale), but it's still functional
  ManifestDPIAware true

!ifndef PORTABLE
  ;Default installation folder
  InstallDir "$PROGRAMFILES\${PACKAGE_NAME}-${PACKAGE_VERSION}"
  ;Get installation folder from registry if available
  InstallDirRegKey HKLM "Software\${PACKAGE_NAME}-${PACKAGE_VERSION}" ""
  ;Request application privileges for Windows Vista
  RequestExecutionLevel admin
!else
  RequestExecutionLevel user
!endif

;--------------------------------
;Versioninfo

VIProductVersion "${VERSIONNUM}"
VIAddVersionKey "CompanyName"      "Warzone 2100 Project"
VIAddVersionKey "FileDescription"  "${PACKAGE_NAME} Installer"
VIAddVersionKey "FileVersion"      "${PACKAGE_VERSION}"
VIAddVersionKey "InternalName"     "${PACKAGE_NAME}"
VIAddVersionKey "LegalCopyright"   "Copyright (c) 2006-2018 Warzone 2100 Project"
VIAddVersionKey "OriginalFilename" "${PACKAGE}-${PACKAGE_VERSION}.exe"
VIAddVersionKey "ProductName"      "${PACKAGE_NAME}"
VIAddVersionKey "ProductVersion"   "${PACKAGE_VERSION}"

;--------------------------------
;Variables

!ifndef PORTABLE
  Var MUI_TEMP
  Var STARTMENU_FOLDER
!endif

;--------------------------------
;Interface Settings

!ifndef PORTABLE
  !define MUI_HEADERIMAGE
  !define MUI_HEADERIMAGE_BITMAP "${TOP_SRCDIR}\icons\wz2100header.bmp"
  !define MUI_HEADERIMAGE_RIGHT
  !define MUI_WELCOMEPAGE_TITLE "Welcome to Warzone 2100 v. ${PACKAGE_VERSION}"
  !define MUI_WELCOMEFINISHPAGE_BITMAP "${TOP_SRCDIR}\icons\wz2100welcome.bmp"
  !define MUI_UNWELCOMEFINISHPAGE_BITMAP "${TOP_SRCDIR}\icons\wz2100welcome.bmp"
  !define MUI_ICON "${TOP_SRCDIR}\icons\warzone2100.ico"
  !define MUI_UNICON "${TOP_SRCDIR}\icons\warzone2100.uninstall.ico"
 !else
  !define MUI_HEADERIMAGE
  !define MUI_HEADERIMAGE_BITMAP "${TOP_SRCDIR}\icons\wz2100headerP.bmp"
  !define MUI_HEADERIMAGE_RIGHT
  !define MUI_WELCOMEPAGE_TITLE "Warzone 2100 v. ${PACKAGE_VERSION} Portable"
  !define MUI_WELCOMEFINISHPAGE_BITMAP "${TOP_SRCDIR}\icons\wz2100welcomeP.bmp"
  !define MUI_UNWELCOMEFINISHPAGE_BITMAP "${TOP_SRCDIR}\icons\wz2100welcomeP.bmp"
  !define MUI_ICON "${TOP_SRCDIR}\icons\wz2100portable.ico"
  !define MUI_UNICON "${TOP_SRCDIR}\icons\wz2100portableU.ico"
!endif

  !define MUI_WELCOMEPAGE_TEXT   "$(WZWelcomeText)"
  !define MUI_ABORTWARNING

!ifndef PORTABLE
  ;Start Menu Folder Page Configuration (for MUI_PAGE_STARTMENU)
  !define MUI_STARTMENUPAGE_REGISTRY_ROOT "HKLM"
  !define MUI_STARTMENUPAGE_REGISTRY_KEY "Software\${PACKAGE_NAME}-${PACKAGE_VERSION}"
  !define MUI_STARTMENUPAGE_REGISTRY_VALUENAME "Start Menu Folder"
!endif
  ; These indented statements modify settings for MUI_PAGE_FINISH
  !define MUI_FINISHPAGE_NOAUTOCLOSE
  !define MUI_UNFINISHPAGE_NOAUTOCLOSE

  !define MUI_LICENSEPAGE_RADIOBUTTONS
  !define MUI_LICENSEPAGE_RADIOBUTTONS_TEXT_ACCEPT "$(WZ_GPL_NEXT)"

  @CPACK_NSIS_DEFINES@
  !define VERSION "@CPACK_PACKAGE_VERSION@"
  !define PATCH  "@CPACK_PACKAGE_VERSION_PATCH@"
  !define INST_DIR "@CPACK_TEMPORARY_DIRECTORY@"

;--------------------------------
; Installation types
@CPACK_NSIS_INSTALLATION_TYPES@

;--------------------------------
; Component sections
@CPACK_NSIS_COMPONENT_SECTIONS@

;--------------------------------
;Pages

  !define MUI_PAGE_CUSTOMFUNCTION_PRE WelcomePageSetupLinkPre
  !define MUI_PAGE_CUSTOMFUNCTION_SHOW WelcomePageSetupLinkShow
  !insertmacro MUI_PAGE_WELCOME
  !insertmacro MUI_PAGE_LICENSE "${TOP_SRCDIR}\COPYING"
  !insertmacro MUI_PAGE_COMPONENTS
  !insertmacro MUI_PAGE_DIRECTORY
!ifndef PORTABLE
  !insertmacro MUI_PAGE_STARTMENU "Application" $STARTMENU_FOLDER
!endif
  !insertmacro MUI_PAGE_INSTFILES
  !insertmacro MUI_PAGE_FINISH

  !insertmacro MUI_UNPAGE_WELCOME
  !insertmacro MUI_UNPAGE_CONFIRM
  !insertmacro MUI_UNPAGE_INSTFILES
  !insertmacro MUI_UNPAGE_FINISH

;--------------------------------
;Languages

  !insertmacro MUI_LANGUAGE "English" # first language is the default language
  !insertmacro MUI_LANGUAGE "Dutch"
  !insertmacro MUI_LANGUAGE "German"
  !insertmacro MUI_LANGUAGE "Russian"

;--------------------------------
;Reserve Files

  ;These files should be inserted before other files in the data block
  ;Keep these lines before any File command
  ;Only for solid compression (by default, solid compression is enabled for BZIP2 and LZMA)

  !insertmacro MUI_RESERVEFILE_LANGDLL
Function WelcomePageSetupLinkPre
  !insertmacro MUI_INSTALLOPTIONS_WRITE "ioSpecial.ini" "Field 3" "Bottom" "142" ; limit size of the upper label
  !insertmacro MUI_INSTALLOPTIONS_WRITE "ioSpecial.ini" "Settings" "Numfields" "4" ; increase counter
  !insertmacro MUI_INSTALLOPTIONS_WRITE "ioSpecial.ini" "Field 4" "Type" "Link"
  !insertmacro MUI_INSTALLOPTIONS_WRITE "ioSpecial.ini" "Field 4" "Text" "Visit our Official Homepage http://wz2100.net for the latest version."
  !insertmacro MUI_INSTALLOPTIONS_WRITE "ioSpecial.ini" "Field 4" "State" "http://wz2100.net/"
  !insertmacro MUI_INSTALLOPTIONS_WRITE "ioSpecial.ini" "Field 4" "Left" "120"
  !insertmacro MUI_INSTALLOPTIONS_WRITE "ioSpecial.ini" "Field 4" "Right" "300"
  !insertmacro MUI_INSTALLOPTIONS_WRITE "ioSpecial.ini" "Field 4" "Top" "154"
  !insertmacro MUI_INSTALLOPTIONS_WRITE "ioSpecial.ini" "Field 4" "Bottom" "172"
FunctionEnd

Function WelcomePageSetupLinkShow
  Push $0
  GetDlgItem $0 $MUI_HWND 1203
  SetCtlColors $0 "0000FF" "FFFFFF"
  ; underline font
  CreateFont $1 "$(^Font)" "$(^FontSize)" "400" /UNDERLINE
  SendMessage $0 ${WM_SETFONT} $1 1
  Pop $0
FunctionEnd

;--------------------------------
;Installer Sections

Section # hidden section, required
  SectionIn RO
  SetOutPath "$INSTDIR"
  SetShellVarContext all

  @CPACK_NSIS_EXTRA_PREINSTALL_COMMANDS@
  @CPACK_NSIS_FULL_INSTALL@

  ;ADD YOUR OWN FILES HERE...

!ifdef INSTALLVIDS
; sequences.wz
  File "${EXTDIR}\opt\sequences.wz"
!endif

!ifndef PORTABLE

  ;Store installation folder
  WriteRegStr HKLM "Software\${PACKAGE_NAME}-${PACKAGE_VERSION}" "" $INSTDIR

  ; Write the Windows-uninstall keys
  WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PACKAGE_NAME}-${PACKAGE_VERSION}" "DisplayName" "${PACKAGE_NAME}-${PACKAGE_VERSION}"
  WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PACKAGE_NAME}-${PACKAGE_VERSION}" "DisplayVersion" "${PACKAGE_VERSION}"
  WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PACKAGE_NAME}-${PACKAGE_VERSION}" "DisplayIcon" "$INSTDIR\bin\${PACKAGE}.exe,0"
  WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PACKAGE_NAME}-${PACKAGE_VERSION}" "Publisher" "Warzone 2100 Project"
  WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PACKAGE_NAME}-${PACKAGE_VERSION}" "URLInfoAbout" "${PACKAGE_BUGREPORT}"
  WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PACKAGE_NAME}-${PACKAGE_VERSION}" "InstallLocation" "$INSTDIR"
  WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PACKAGE_NAME}-${PACKAGE_VERSION}" "UninstallString" "$INSTDIR\uninstall.exe"
  WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PACKAGE_NAME}-${PACKAGE_VERSION}" "NoModify" 1
  WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PACKAGE_NAME}-${PACKAGE_VERSION}" "NoRepair" 1

  ;Create uninstaller
  WriteUninstaller "$INSTDIR\uninstall.exe"

  !insertmacro MUI_STARTMENU_WRITE_BEGIN Application
    SetOutPath "$INSTDIR"
    ;Create shortcuts
    CreateDirectory "$SMPROGRAMS\$STARTMENU_FOLDER-${PACKAGE_VERSION}"
    CreateShortCut "$SMPROGRAMS\$STARTMENU_FOLDER-${PACKAGE_VERSION}\Uninstall.lnk" "$INSTDIR\uninstall.exe"
    CreateShortCut "$SMPROGRAMS\$STARTMENU_FOLDER-${PACKAGE_VERSION}\${PACKAGE_NAME}.lnk" "$INSTDIR\bin\${PACKAGE}.exe"
    CreateShortCut "$SMPROGRAMS\$STARTMENU_FOLDER-${PACKAGE_VERSION}\Quick Start Guide (html).lnk" "$INSTDIR\doc\quickstartguide.html"

  !insertmacro MUI_STARTMENU_WRITE_END

  SetOutPath "$INSTDIR"
  CreateShortCut "$DESKTOP\${PACKAGE_NAME}-${PACKAGE_VERSION}.lnk" "$INSTDIR\bin\${PACKAGE}.exe"

!endif #PORTABLE

@CPACK_NSIS_EXTRA_INSTALL_COMMANDS@

SectionEnd

; NOTE: you need upgraded security privs to install shortcut on desktop for portable.

!macro DownloadMSSysLib URL Caption OutputFile ExpectedFileDescriptionPrefix Result
inetc::get /CAPTION "${Caption}" "${URL}" "${OutputFile}"
Pop $R0 # return value = exit code, "OK" if OK
${If} $R0 == "OK"
  ; Download succeeded - check file
  filecheck::verifyFileSignature "${OutputFile}" /ROOT "microsoft" /CERTNAME "Microsoft Corporation" /CERTISSUERNAME "Microsoft Code Signing PCA"
  Pop $R0 ; Get the return value
  ${If} $R0 == "OK"
	filecheck::getFileVersionInfoString "${OutputFile}" "FileDescription" /LANGUAGE 1033 /CODEPAGE 1252
	Pop $R0 ; Get the return value
	${StrLoc} $R1 "$R0" "${ExpectedFileDescriptionPrefix}" ">"
	${If} $R1 == 0
	  ; Passed code signature & file version info checks
      StrCpy ${Result} "OK"
    ${Else}
      ; File version info did not match expected
      StrCpy ${Result} "FILE_INFO"
	${EndIf}
  ${Else}
	; Failed to verify file code signature
    ; MessageBox MB_OK|MB_ICONSTOP "Download of system library failed: CODE_SIGNATURE"
    StrCpy ${Result} "CODE_SIGNATURE"
  ${EndIf}
${Else}
  ; Download failed
  ; MessageBox MB_OK|MB_ICONSTOP "Download of system library failed: $R0"
  StrCpy ${Result} $R0
${EndIf}
!macroend

!macro DownloadFile URL Caption OutputFile ExpectedSHA512Hash Result
DetailPrint "Downloading ${URL} ..."
inetc::get /CAPTION "${Caption}" "${URL}" "${OutputFile}"
Pop $R0 # return value = exit code, "OK" if OK
${If} $R0 == "OK"
  ; Download succeeded - check file hash
  filecheck::calcFileHash "${OutputFile}" sha512
  Pop $R0 ; Get the return value
  ${If} $R0 == "${ExpectedSHA512Hash}"
    ; Passed hash check
    StrCpy ${Result} "OK"
  ${Else}
    ; Failed to verify file hash
    ; MessageBox MB_OK|MB_ICONSTOP "Download of file failed: UNEXPECTED_HASH"
    StrCpy ${Result} "UNEXPECTED_HASH"
  ${EndIf}
${Else}
  ; Download failed
  ; MessageBox MB_OK|MB_ICONSTOP "Download of file failed: $R0"
  StrCpy ${Result} $R0
${EndIf}
!macroend

!macro HTTPDownloadFile URL Caption OutputFile ExpectedHashType ExpectedHash Result
; Note: Caption is currently ignored
DetailPrint "Downloading ${URL} ..."
NSISdl::download "${URL}" "${OutputFile}"
Pop $R0 # return value, "success" if OK
${If} $R0 == "success"
  ; Download succeeded - check file hash
  filecheck::calcFileHash "${OutputFile}" "${ExpectedHashType}"
  Pop $R0 ; Get the return value
  ${If} $R0 == "${ExpectedHash}"
    ; Passed hash check
    StrCpy ${Result} "OK"
  ${Else}
    ; Failed to verify file hash
    ; MessageBox MB_OK|MB_ICONSTOP "Download of file failed: UNEXPECTED_HASH"
    StrCpy ${Result} "UNEXPECTED_HASH"
  ${EndIf}
${Else}
  ; NSISdl::download failed
  ; MessageBox MB_OK|MB_ICONSTOP "Download of file failed: $R0"
  ${IfNot} $R0 == "OK"
    StrCpy ${Result} "$R0"
  ${Else}
    StrCpy ${Result} "NSISdl::download failed"
  ${EndIf}
${EndIf}
!macroend

!macro DownloadFile2 URL URLAlt URLHTTPAlt Caption OutputFile ExpectedSHA512Hash Result
!insertmacro DownloadFile "${URL}" "${Caption}" "${OutputFile}" "${ExpectedSHA512Hash}" ${Result}
${IfNot} ${Result} == "OK"
  DetailPrint "Download attempt (1) from ${URL} failed with error: ${Result}."
  !insertmacro DownloadFile "${URLAlt}" "${Caption}" "${OutputFile}" "${ExpectedSHA512Hash}" ${Result}
  ${IfNot} ${Result} == "OK"
    DetailPrint "Download attempt (2) from ${URLAlt} failed with error: ${Result}."
    ; Make one more attempt, this time with the HTTP URL (required for some versions of Windows < 10, depending on server + client settings and patches installed)
    !insertmacro HTTPDownloadFile "${URLHTTPAlt}" "${Caption}" "${OutputFile}" "sha512" "${ExpectedSHA512Hash}" ${Result}
    ${IfNot} ${Result} == "OK"
      DetailPrint "Download attempt (3) (HTTP) from ${URLHTTPAlt} failed with error: ${Result}."
    ${EndIf}
  ${EndIf}
${EndIf}
!macroend

!ifdef MSVCRUNTIME
  Var MSVCRT15_x86_NotPresent
  Var MSVCRT15_x64_NotPresent
  Var Result_MSVCDownload

  !ifndef PORTABLE
    ; Provide option to download and install missing / outdated system libraries
    Section "" SecMSSysLibraries
      SetOutPath "$INSTDIR"

      ${If} $MSVCRT15_x86_NotPresent == 1
        !insertmacro DownloadMSSysLib "https://aka.ms/vs/15/release/vc_redist.x86.exe" "Downloading vc_redist.x86.exe" "$PLUGINSDIR\vc_redist.x86.exe" "Microsoft Visual C++ 2017 Redistributable" $Result_MSVCDownload
        ${If} $Result_MSVCDownload == "OK"
          ; Download succeeded
          DetailPrint "vc_redist.x86.exe ..."
          ExecWait '"$PLUGINSDIR\vc_redist.x86.exe" /q'
        ${Else}
          MessageBox MB_OK|MB_ICONSTOP "Download of system library (x86) failed: $Result_MSVCDownload"
        ${EndIf}
      ${EndIf}
	  ${If} ${RunningX64}
      ${AndIf} $MSVCRT15_x64_NotPresent == 1
        !insertmacro DownloadMSSysLib "https://aka.ms/vs/15/release/vc_redist.x64.exe" "Downloading vc_redist.x64.exe" "$PLUGINSDIR\vc_redist.x64.exe" "Microsoft Visual C++ 2017 Redistributable" $Result_MSVCDownload
        ${If} $Result_MSVCDownload == "OK"
          ; Download succeeded
          DetailPrint "vc_redist.x64.exe ..."
          ExecWait '"$PLUGINSDIR\vc_redist.x64.exe" /q'
        ${Else}
          MessageBox MB_OK|MB_ICONSTOP "Download of system library (x64) failed: $Result_MSVCDownload"
        ${EndIf}
      ${EndIf}
    SectionEnd
  !else
    ; For Portable installer, provide option to download app-local system runtimes
    Section "" SecMSSysLibraries
      SetOutPath "$INSTDIR"

      !insertmacro DownloadFile2 "${MSVCRT_PORTABLE_DL_URL1}" "${MSVCRT_PORTABLE_DL_URL2}" "${MSVCRT_PORTABLE_DL_URL_HTTPALT}" "${MSVCRT_PORTABLE_DL_CAPTION}" "$PLUGINSDIR\applocaldl.zip" "${MSVCRT_PORTABLE_DL_SHA512}" $Result_MSVCDownload
      ${If} $Result_MSVCDownload == "OK"
        ; Download succeeded
        nsisunz::UnzipToLog "$PLUGINSDIR\applocaldl.zip" "$INSTDIR\bin"
        Pop $0 ; Get the return value
        ${IfNot} $0 == "success"
          ; Failed to unzip downloaded file
          DetailPrint "$0" ; print error message to log
        ${EndIf}
      ${Else}
        MessageBox MB_OK|MB_ICONSTOP "Download of applocal system library (x86) failed: $Result_MSVCDownload"
      ${EndIf}

      ; TODO: In the future, also support downloading the x64 applocal runtimes?
    SectionEnd
  !endif
!endif

!ifndef INSTALLVIDS
SectionGroup $(TEXT_SecFMVs) SecFMVs

Section /o $(TEXT_SecFMVs_EngHi) SecFMVs_EngHi
  SetOutPath "$INSTDIR"
  IfFileExists "sequences.wz" +5
    NSISdl::download "http://downloads.sourceforge.net/project/warzone2100/warzone2100/Videos/high-quality-en/sequences.wz"               "sequences.wz"
    Pop $R0 ; Get the return value
    StrCmp $R0 "success" +2
      MessageBox MB_OK|MB_ICONSTOP "Download of videos failed: $R0"
SectionEnd

Section /o $(TEXT_SecFMVs_Eng) SecFMVs_Eng
  SetOutPath "$INSTDIR"
  IfFileExists "sequences.wz" +5
    NSISdl::download "http://downloads.sourceforge.net/project/warzone2100/warzone2100/Videos/standard-quality-en/sequences.wz"               "sequences.wz"
    Pop $R0 ; Get the return value
    StrCmp $R0 "success" +2
      MessageBox MB_OK|MB_ICONSTOP "Download of videos failed: $R0"
SectionEnd

Section /o $(TEXT_SecFMVs_EngLo) SecFMVs_EngLo
  SetOutPath "$INSTDIR"
  IfFileExists "sequences.wz" +5
    NSISdl::download "http://downloads.sourceforge.net/project/warzone2100/warzone2100/Videos/low-quality-en/sequences.wz"               "sequences.wz"
    Pop $R0 ; Get the return value
    StrCmp $R0 "success" +2
      MessageBox MB_OK|MB_ICONSTOP "Download of videos failed: $R0"
SectionEnd

;Section /o $(TEXT_SecFMVs_Ger) SecFMVs_Ger
;  SetOutPath "$INSTDIR"
;  IfFileExists "sequences.wz" +5
;    NSISdl::download "http://download.gna.org/warzone/videos/2.2/warzone2100-sequences-ger-hi-2.2.wz"               "sequences.wz"
;    Pop $R0 ; Get the return value
;    StrCmp $R0 "success" +2
;      MessageBox MB_OK|MB_ICONSTOP "Download of videos failed: $R0"
;
;SectionEnd

SectionGroupEnd
!endif


;--------------------------------
;Installer Functions

Function .onInit

  ; Initialize the plugins dir (important)
  InitPluginsDir

  !insertmacro MUI_LANGDLL_DISPLAY
!ifndef INSTALLVIDS
  # increase required size of section 'SecFMVs_EngHi' by file size
  SectionGetSize ${SecFMVs_EngHi} $0
  IntOp $0 $0 + 671938;135
  SectionSetSize ${SecFMVs_EngHi} $0

  # increase required size of section 'SecFMVs_Eng' by file size
  SectionGetSize ${SecFMVs_Eng} $0
  IntOp $0 $0 + 571937;134
  SectionSetSize ${SecFMVs_Eng} $0

  # increase required size of section 'SecFMVs_EngLo' by file size
  SectionGetSize ${SecFMVs_EngLo} $0
  IntOp $0 $0 + 165681;436
  SectionSetSize ${SecFMVs_EngLo} $0

  # increase required size of section 'SecFMVs_Ger' by file size
;  SectionGetSize ${SecFMVs_Ger} $0
;  IntOp $0 $0 + 499187;492
;  SectionSetSize ${SecFMVs_Ger} $0

  ;HACK: Set section 'Video' as read-only
  SectionGetFlags ${SecFMVs} $0
  IntOp $0 $0 ^ ${SF_SELECTED}
  IntOp $0 $0 | ${SF_RO}
  SectionSetFlags ${SecFMVs} $0

  ;FIXME: Select default video sub-component
  ; Default is still set to standard instead of high, since there is a ~450MB difference
  StrCpy $5 ${SecFMVs_Eng}

  ; Determine whether Microsoft system libraries are installed
  !ifdef MSVCRUNTIME
    StrCpy $MSVCRT15_x86_NotPresent 0
    StrCpy $MSVCRT15_x64_NotPresent 0

    !ifndef PORTABLE

      ; Check for presence of MSVC++ 14 System Runtime (VC2017, works with 2015)
      ; NOTE: Because VC 15 is ABI compatible with VC 14, the version # used is still 14.
      ; The VCRuntime includes the Universal C Runtime system component (the UCRT does not have to be detected / handled separately)
      !ifndef MSVCRT14_BLD_MINIMUM
        !error "MSVCRT14_BLD_MINIMUM is not defined"
      !endif

      ${If} ${RunningX64}
        SetRegView 64
        ReadRegDword $R1 HKLM "SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\x64" "Bld"
        SetRegView lastused
        ;MessageBox MB_OK|MB_ICONSTOP "x64 VC14 Runtime Bld: $R1"
        ${If} $R1 < ${MSVCRT14_BLD_MINIMUM}
          StrCpy $MSVCRT15_x64_NotPresent 1
        ${EndIf}
      ${EndIf}
      StrCpy $R1 ""
      SetRegView 32
      ReadRegDword $R1 HKLM "SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\x86" "Bld"
      ; MessageBox MB_OK|MB_ICONSTOP "x86 VC14 Runtime Bld: $R1"
      SetRegView lastused
      ${If} $R1 < ${MSVCRT14_BLD_MINIMUM}
        StrCpy $MSVCRT15_x86_NotPresent 1
      ${EndIf}

      ${If} $MSVCRT15_x64_NotPresent = 1
      ${OrIf} $MSVCRT15_x86_NotPresent = 1
        SectionSetText ${SecMSSysLibraries} "$(TEXT_SecMSSysLibraries)"
        ; very rough estimate - we can't know exactly how much space will be taken up, but it's better to signify *something*
        SectionSetSize ${SecMSSysLibraries} 10000
      ${Else}
        !insertmacro UnSelectSection ${SecMSSysLibraries}
        SectionSetText ${SecMSSysLibraries} ""
      ${EndIf}

    !else

      ; For Portable builds, always offer the option
      SectionSetText ${SecMSSysLibraries} "$(TEXT_SecMSSysLibraries)"
      ; rough estimate
      SectionSetSize ${SecMSSysLibraries} 3000

    !endif
  !endif

!endif

!ifdef PORTABLE
 System::Call "kernel32::GetCurrentDirectory(i ${NSIS_MAX_STRLEN}, t .r0)"
 GetFullPathName $0 "$0\"
 StrCpy $INSTDIR "$0${PACKAGE_NAME}-${PACKAGE_VERSION}\"
!endif
FunctionEnd

!ifndef INSTALLVIDS
Function .onSelChange
${If} ${SectionIsSelected} ${SecFMVs_Eng}
${OrIf} ${SectionIsSelected} ${SecFMVs_EngHi}
${OrIf} ${SectionIsSelected} ${SecFMVs_EngLo}
;${OrIf} ${SectionIsSelected} ${SecFMVs_Ger}
  !insertmacro StartRadioButtons $5
    !insertmacro RadioButton ${SecFMVs_EngHi}
    !insertmacro RadioButton ${SecFMVs_Eng}
    !insertmacro RadioButton ${SecFMVs_EngLo}
;   !insertmacro RadioButton ${SecFMVs_Ger}
  !insertmacro EndRadioButtons
${EndIf}
FunctionEnd
!endif


;--------------------------------
;Descriptions

  !include "..\..\..\Lang-English.nsh"
  !include "..\..\..\Lang-Dutch.nsh"
  !include "..\..\..\Lang-German.nsh"
  !include "..\..\..\Lang-Russian.nsh"

  ;Assign language strings to sections
  !insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN
    !insertmacro MUI_DESCRIPTION_TEXT ${Core} "$(DESC_SecBase)"
    !insertmacro MUI_DESCRIPTION_TEXT ${Languages} "$(DESC_SecNLS)"

    !insertmacro MUI_DESCRIPTION_TEXT ${SecFMVs} $(DESC_SecFMVs)
    !insertmacro MUI_DESCRIPTION_TEXT ${SecFMVs_Eng} $(DESC_SecFMVs_Eng)
    !insertmacro MUI_DESCRIPTION_TEXT ${SecFMVs_EngHi} $(DESC_SecFMVs_EngHi)
    !insertmacro MUI_DESCRIPTION_TEXT ${SecFMVs_EngLo} $(DESC_SecFMVs_EngLo)
;    !insertmacro MUI_DESCRIPTION_TEXT ${SecFMVs_Ger} $(DESC_SecFMVs_Ger)

    !insertmacro MUI_DESCRIPTION_TEXT ${SecNLS_WinFonts} $(DESC_SecNLS_WinFonts)

    !ifdef MSVCRUNTIME
    !insertmacro MUI_DESCRIPTION_TEXT ${SecMSSysLibraries} $(DESC_SecMSSysLibraries)
    !endif
  !insertmacro MUI_FUNCTION_DESCRIPTION_END


;--------------------------------
;Uninstaller Section
!ifndef PORTABLE

Section "Uninstall"

  @CPACK_NSIS_EXTRA_UNINSTALL_COMMANDS@

  ;ADD YOUR OWN FILES HERE...

  @CPACK_NSIS_DELETE_FILES@
  @CPACK_NSIS_DELETE_DIRECTORIES@

  Delete "$INSTDIR\sequences.wz"

  Delete "$INSTDIR\stderr.txt"
  Delete "$INSTDIR\stdout.txt"

  Delete "$INSTDIR\License.txt"

  Delete "$INSTDIR\uninstall.exe"

  RMDir "$INSTDIR"

  SetShellVarContext all

; remove the desktop shortcut icon

  Delete "$DESKTOP\${PACKAGE_NAME}-${PACKAGE_VERSION}.lnk"

; and now, lets really remove the startmenu entries...

  !insertmacro MUI_STARTMENU_GETFOLDER Application $MUI_TEMP

  Delete "$SMPROGRAMS\$MUI_TEMP-${PACKAGE_VERSION}\Uninstall.lnk"
  Delete "$SMPROGRAMS\$MUI_TEMP-${PACKAGE_VERSION}\${PACKAGE_NAME}.lnk"
  Delete "$SMPROGRAMS\$MUI_TEMP-${PACKAGE_VERSION}\Quick Start Guide (html).lnk"

  ;Delete empty start menu parent directories
  StrCpy $MUI_TEMP "$SMPROGRAMS\$MUI_TEMP-${PACKAGE_VERSION}"

  startMenuDeleteLoop:
    ClearErrors
    RMDir $MUI_TEMP
    GetFullPathName $MUI_TEMP "$MUI_TEMP\.."

    IfErrors startMenuDeleteLoopDone

    StrCmp $MUI_TEMP $SMPROGRAMS startMenuDeleteLoopDone startMenuDeleteLoop
  startMenuDeleteLoopDone:

  DeleteRegValue HKLM "Software\${PACKAGE_NAME}-${PACKAGE_VERSION}" "Start Menu Folder"
  DeleteRegValue HKLM "Software\${PACKAGE_NAME}-${PACKAGE_VERSION}" ""
  DeleteRegKey /ifempty HKLM "Software\${PACKAGE_NAME}-${PACKAGE_VERSION}"

  ; Unregister with Windows' uninstall system
  DeleteRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PACKAGE_NAME}-${PACKAGE_VERSION}"

SectionEnd
!endif

;--------------------------------
;Uninstaller Functions

!ifndef PORTABLE
Function un.onInit
  !verbose push
  !verbose push
  !insertmacro MUI_UNGETLANGUAGE
FunctionEnd
!endif
