!macro GITTY_MIGRATE_LEGACY_DATA_DIR oldDir newDir
  ${IfNot} ${FileExists} "${newDir}\*.*"
  ${AndIf} ${FileExists} "${oldDir}\*.*"
    Rename "${oldDir}" "${newDir}"
  ${EndIf}
!macroend

!macro GITTY_UNINSTALL_LEGACY_GITLITE rootKey
  ClearErrors
  ReadRegStr $R0 ${rootKey} "Software\Microsoft\Windows\CurrentVersion\Uninstall\GitLite" "UninstallString"
  ${If} "$R0" != ""
    ReadRegStr $R1 ${rootKey} "Software\git-lite\GitLite" ""
    ${If} "$R1" == ""
      ReadRegStr $R1 ${rootKey} "Software\Microsoft\Windows\CurrentVersion\Uninstall\GitLite" "InstallLocation"
    ${EndIf}

    DetailPrint "Removing legacy GitLite installation"
    ${If} "$R1" != ""
      ExecWait '$R0 /S _?=$R1' $R2
    ${Else}
      ExecWait '$R0 /S' $R2
    ${EndIf}
  ${EndIf}

  DeleteRegKey ${rootKey} "Software\Microsoft\Windows\CurrentVersion\Uninstall\GitLite"
  DeleteRegKey ${rootKey} "Software\git-lite\GitLite"
  DeleteRegKey /ifempty ${rootKey} "Software\git-lite"
!macroend

!macro GITTY_CLEANUP_LEGACY_SHORTCUTS
  Delete "$DESKTOP\GitLite.lnk"
  Delete "$SMPROGRAMS\GitLite.lnk"
  RMDir /r "$SMPROGRAMS\GitLite"
!macroend

!macro GITTY_REGISTER_INSTALL
  WriteRegStr HKCU "${MANUPRODUCTKEY}" "" "$INSTDIR"
  WriteRegStr HKCU "${UNINSTKEY}" "MainBinaryName" "${MAINBINARYNAME}.exe"
  WriteRegStr HKCU "${UNINSTKEY}" "DisplayName" "${PRODUCTNAME}"
  WriteRegStr HKCU "${UNINSTKEY}" "DisplayIcon" "$\"$INSTDIR\${MAINBINARYNAME}.exe$\""
  WriteRegStr HKCU "${UNINSTKEY}" "DisplayVersion" "${VERSION}"
  WriteRegStr HKCU "${UNINSTKEY}" "Publisher" "${MANUFACTURER}"
  WriteRegStr HKCU "${UNINSTKEY}" "InstallLocation" "$\"$INSTDIR$\""
  WriteRegStr HKCU "${UNINSTKEY}" "UninstallString" "$\"$INSTDIR\uninstall.exe$\""
  WriteRegStr HKCU "${UNINSTKEY}" "QuietUninstallString" "$\"$INSTDIR\uninstall.exe$\" /S"
  WriteRegDWORD HKCU "${UNINSTKEY}" "NoModify" "1"
  WriteRegDWORD HKCU "${UNINSTKEY}" "NoRepair" "1"
!macroend

!macro GITTY_CREATE_UPDATE_SHORTCUTS
  CreateShortcut "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
  !insertmacro SetLnkAppUserModelId "$SMPROGRAMS\${PRODUCTNAME}.lnk"
  CreateShortcut "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
  !insertmacro SetLnkAppUserModelId "$DESKTOP\${PRODUCTNAME}.lnk"
!macroend

!macro NSIS_HOOK_PREINSTALL
  !insertmacro GITTY_MIGRATE_LEGACY_DATA_DIR "$APPDATA\com.git-lite" "$APPDATA\com.gitty"
  !insertmacro GITTY_MIGRATE_LEGACY_DATA_DIR "$LOCALAPPDATA\com.git-lite" "$LOCALAPPDATA\com.gitty"
  !insertmacro GITTY_UNINSTALL_LEGACY_GITLITE HKCU
  !insertmacro GITTY_UNINSTALL_LEGACY_GITLITE HKLM
!macroend

!macro NSIS_HOOK_POSTINSTALL
  !insertmacro GITTY_CLEANUP_LEGACY_SHORTCUTS
  !insertmacro GITTY_REGISTER_INSTALL
  !insertmacro GITTY_CREATE_UPDATE_SHORTCUTS
!macroend

!macro NSIS_HOOK_POSTUNINSTALL
  !insertmacro GITTY_CLEANUP_LEGACY_SHORTCUTS
!macroend
