; Language IDs
; 1033 English
; 2052 Simplified Chinese

LangString MyProductName 1033 "iQue@Home"
LangString MyProductName 2052 "神游在线(iQue@Home)"
!define PRODUCT_NAME $(MyProductName)
!define PRODUCT_UNINST_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}"
!define PRODUCT_UNINST_ROOT_KEY "HKLM"
!define MUI_LANGDLL_REGISTRY_ROOT "${PRODUCT_UNINST_ROOT_KEY}"
!define MUI_LANGDLL_REGISTRY_KEY "${PRODUCT_UNINST_KEY}"
!define MUI_LANGDLL_REGISTRY_VALUENAME "NSIS:Language"

;--------------------------------
;Header files

  !include "MUI.nsh"

  !addplugindir "${NSISDIR}\Contrib\NSIS Update"
  !addplugindir "${NSISDIR}\Contrib\ZipDLL"
  !addincludedir "${NSISDIR}\Contrib\ZipDLL"

  !include "ZipDLL.nsh"

;--------------------------------
;Configuration

  LangString MyName 1033 "iQue@Home Update"
  LangString MyName 2052 "神游在线(iQue@home)联网更新"
  Name $(MyName)
  LangString MyCaption 1033 "iQue@Home Update"
  LangString MyCaption 2052 "神游在线(iQue@home)联网更新"
  Caption $(MyCaption)
  OutFile "\Update.exe"
  BrandingText " "

  LangString MyInstallButtonText 1033 "Update"
  LangString MyInstallButtonText 2052 "联网更新"
  InstallButtonText $(MyInstallButtonText)
  ShowInstDetails nevershow
  InstallColors /windows
  InstallDirRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\App Paths\iqahc.exe" ""
  
  !define DEFAULT_SERVER "rms.idc.ique.com"

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

  Var TEMP1
  Var TEMP2
  Var TEMP3
  Var MODNAME
  Var MODREV
  Var DODOWNLOAD
  Var LAUNCHER

  Var MYVERSION
  Var NEWVERSION
  Var SERVER

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

  !define MUI_ICON "update48.ico"
!define MUI_HEADERIMAGE
!define MUI_HEADERIMAGE_BITMAP_NOSTRETCH
!define MUI_HEADERIMAGE_BITMAP "..\..\..\NetCard0524\BMP\head2.bmp"

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

  Page custom UpdateMethod UpdateLeave
  
  !define MUI_PAGE_HEADER_TEXT ""
  !define MUI_PAGE_HEADER_SUBTEXT ""
  LangString MyINSTFILESPAGE_FINISHHEADER_TEXT 1033 "Task Completed"
  LangString MyINSTFILESPAGE_FINISHHEADER_TEXT 2052 "更新完成"
  !define MUI_INSTFILESPAGE_FINISHHEADER_TEXT $(MyINSTFILESPAGE_FINISHHEADER_TEXT)
  LangString MyINSTFILESPAGE_FINISHHEADER_SUBTEXT 1033 "See the log window below for details."
  LangString MyINSTFILESPAGE_FINISHHEADER_SUBTEXT 2052 "查看日志窗口以获取详细资料。"
  !define MUI_INSTFILESPAGE_FINISHHEADER_SUBTEXT $(MyINSTFILESPAGE_FINISHHEADER_SUBTEXT)
  LangString MyINSTFILESPAGE_ABORTHEADER_TEXT 1033 "Error"
  LangString MyINSTFILESPAGE_ABORTHEADER_TEXT 2052 "错误"
  !define MUI_INSTFILESPAGE_ABORTHEADER_TEXT $(MyINSTFILESPAGE_ABORTHEADER_TEXT)
  LangString MyINSTFILESPAGE_ABORTHEADER_SUBTEXT 1033 "Update was not completed succesfully."
  LangString MyINSTFILESPAGE_ABORTHEADER_SUBTEXT 2052 "联网更新没有正确完成。"
  !define MUI_INSTFILESPAGE_ABORTHEADER_SUBTEXT $(MyINSTFILESPAGE_ABORTHEADER_SUBTEXT)

  !insertmacro MUI_PAGE_INSTFILES

;--------------------------------
;Languages
 
  !insertmacro MUI_LANGUAGE "English"
  !insertmacro MUI_LANGUAGE "SimpChinese"

;--------------------------------
;Macros

;--------------------------------
; Functions

Function DoQuit
  Strcmp $LAUNCHER "yes" "" +2
  Exec "$INSTDIR\pkgs\core\bin\iqahc.exe"
  Quit
FunctionEnd

; TrimNewlines
 ; input, top of stack  (e.g. whatever$\r$\n)
 ; output, top of stack (replaces, with e.g. whatever)
 ; modifies no other variables.

Function GetCurrentTime
Push $R0
Push $R1
Push $R2
System::Call '*(&i2, &i2, &i2, &i2, &i2, &i2, &i2, &i2) i .R0'
System::Call 'kernel32::GetLocalTime(i) i(R0)'
System::Call '*$R0(&i2, &i2, &i2, &i2, &i2, &i2, &i2, &i2)(.R0,,,,,,,)'
StrCpy $R1 $R0

System::Call '*(&i2, &i2, &i2, &i2, &i2, &i2, &i2, &i2) i .R0'
System::Call 'kernel32::GetLocalTime(i) i(R0)'
System::Call '*$R0(&i2, &i2, &i2, &i2, &i2, &i2, &i2, &i2)(,.R0,,,,,,)'
StrCpy $R2 $R0 "" 1
StrCmp $R2 "" 0 +2
StrCpy $R0 "0$R0"
StrCpy $R1 "$R1-$R0"

System::Call '*(&i2, &i2, &i2, &i2, &i2, &i2, &i2, &i2) i .R0'
System::Call 'kernel32::GetLocalTime(i) i(R0)'
System::Call '*$R0(&i2, &i2, &i2, &i2, &i2, &i2, &i2, &i2)(,,,.R0,,,,)'
StrCpy $R2 $R0 "" 1
StrCmp $R2 "" 0 +2
StrCpy $R0 "0$R0"
StrCpy $R0 "$R1-$R0"

Pop $R2
Pop $R1
Exch $R0
FunctionEnd

 ; GetParameters
 ; input, none
 ; output, top of stack (replaces, with e.g. whatever)
 ; modifies no other variables.

 Function GetParameters
 ; save the value in R0,R1,R2,R3 onto stack . 
 ; so we can reload the original value back to them after we use them in this function .
   Push $R0
   Push $R1
   Push $R2
   Push $R3

   StrCpy $R2 1
   StrLen $R3 $CMDLINE

   ;Check for quote or space
   StrCpy $R0 $CMDLINE $R2
   StrCmp $R0 '"' 0 +3
     StrCpy $R1 '"'
     Goto loop
   StrCpy $R1 " "

   loop:
     IntOp $R2 $R2 + 1
     StrCpy $R0 $CMDLINE 1 $R2
     StrCmp $R0 $R1 get
     StrCmp $R2 $R3 get
     Goto loop

   get:
     IntOp $R2 $R2 + 1
     StrCpy $R0 $CMDLINE 1 $R2
     StrCmp $R0 " " get
     StrCpy $R0 $CMDLINE "" $R2

   Pop $R3
   Pop $R2
   Pop $R1
   Exch $R0

 FunctionEnd

 Function TrimNewlines
   Exch $R0
   Push $R1
   Push $R2
   StrCpy $R1 0

 loop:
   IntOp $R1 $R1 - 1
   StrCpy $R2 $R0 1 $R1
   StrCmp $R2 "$\r" loop
   StrCmp $R2 "$\n" loop
   IntOp $R1 $R1 + 1
   IntCmp $R1 0 no_trim_needed
   StrCpy $R0 $R0 $R1

 no_trim_needed:
   Pop $R2
   Pop $R1
   Exch $R0
 FunctionEnd

 Function GetValueFromPair
   Exch $R0
   Push $R1

 loop:
   StrCmp $R0 "" done
   StrCpy $R1 $R0 3
   StrCmp $R1 " = " "" +3
     StrCpy $R0 $R0 "" 3
     goto done
   StrCpy $R0 $R0 "" 1
   goto loop
   
 done:
   Pop $R1
   Exch $R0
 FunctionEnd

Function .onInit

  Call GetParameters
  Pop $TEMP1

  System::Call 'kernel32::GetModuleFileNameA(i 0, t .R0, i 1024) i r1'
  
  StrCpy $R0 $R0 "" -10
    StrCmp $R0 "Update.bin" temp
    
    ;Create a temporary file, so Update can update itself
    
    CopyFiles /SILENT "$EXEDIR\Update.exe" "$TEMP\Update.bin"
    Exec '"$TEMP\Update.bin" $TEMP1'
    Quit
    
  temp:
  
  StrCmp "$TEMP1" "launch" "" +3
    StrCpy $LAUNCHER "yes"
    goto +2
    StrCpy $LAUNCHER "no"

  ;Remove temporary file on next reboot
  Delete /REBOOTOK "$TEMP\Update.bin"
  
  StrCmp $LAUNCHER "yes" "" temp2
    Call GetCurrentTime
    Pop $0
    ReadRegStr $TEMP1 HKLM ${PRODUCT_UNINST_KEY} "LastUpdateCheck"
    StrCmp "$0" "$TEMP1" "" +2
      Call DoQuit
    WriteRegStr HKLM ${PRODUCT_UNINST_KEY} "LastUpdateCheck" "$0"
  temp2:

  FileOpen $TEMP1 "$INSTDIR\SERVER" r
  FileRead $TEMP1 $TEMP2
  FileClose $TEMP1
  Push $TEMP2
  Call TrimNewLines
  Pop $TEMP2
  StrCmp $TEMP2 "" "" +3
    StrCpy $SERVER ${DEFAULT_SERVER}
    goto +2
    StrCpy $SERVER $TEMP2

FunctionEnd

Function .onInstSuccess

  Call DoQuit

FunctionEnd

LangString MyHEADER_TEXT1 1033 "Update Method"
LangString MyHEADER_TEXT1 2052 "更新方式"
LangString MyHEADER_TEXT2 1033 "Click next to check for updates."
LangString MyHEADER_TEXT2 2052 "点击下一步检测更新。"
Function UpdateMethod

  !insertmacro MUI_HEADER_TEXT $(MyHEADER_TEXT1) $(MyHEADER_TEXT2)
  !insertmacro MUI_INSTALLOPTIONS_DISPLAY "Method.ini"

FunctionEnd

Function UpdateLeave

  !insertmacro MUI_INSTALLOPTIONS_READ $TEMP1 "Method.ini" "Field 1" "State"

FunctionEnd

Function CloseMenu

  loop:
    FindWindow $TEMP1 "iQue@homeMainWnd"
    IntCmp $TEMP1 0 done
      SendMessage $TEMP1 ${WM_CLOSE} 0 0
    Sleep 100
    Goto loop
  done:

FunctionEnd

LangString MyCannotConnect 1033 "Cannot connect to the internet."
LangString MyCannotConnect 2052 "无法连接到互联网。"
LangString MyPleaseConnect 1033 "Please connect to the internet now."
LangString MyPleaseConnect 2052 "请连接互联网。"
Function ConnectInternet

  Push $R0
    
    ClearErrors
    Dialer::AttemptConnect
    IfErrors noie3
    
    Pop $R0
    StrCmp $R0 "online" connected
      MessageBox MB_OK|MB_ICONSTOP $(MyCannotConnect)
      Call DoQuit
    
    noie3:
  
    ; IE3 not installed
    MessageBox MB_OK|MB_ICONINFORMATION $(MyPleaseConnect)
    
    connected:
  
  Pop $R0
  
FunctionEnd


;--------------------------------
; Update (Installer Section)

LangString MyChkNew1 1033 "Checking for a release..."
LangString MyChkNew1 2052 "检测联网更新..."
LangString MyChkNew2 1033 "Please wait while Update checks whether a new release is available."
LangString MyChkNew2 2052 "请稍候，联网更新程序正在检测数据中心是否有需要的更新内容。"
LangString MyVersTxt 1033 "Your iQue@home version: $MYVERSION"
LangString MyVersTxt 2052 "您的神游在线(iQue@home)版本号为: $MYVERSION"
LangString MyCheckTxt 1033 "Checking for a new release..."
LangString MyCheckTxt 2052 "检测更新内容..."
LangString MyDLFail 1033 "Download failed: $TEMP1."
LangString MyDLFail 2052 "更新失败: $TEMP1."
LangString MyInvVers 1033 "Invalid version data."
LangString MyInvVers 2052 "无效的更新数据。"
LangString MyStaVers 1033 "A new stable release is available: $NEWVERSION"
LangString MyStaVers 2052 "检测到有效的更新内容: $NEWVERSION"
LangString MyNoRel 1033 "No new release is available. Please check again later."
LangString MyNoRel 2052 "目前没有新的有效更新内容，请稍候再尝试检测。"
LangString MyNewRel 1033 "A new release is available. Would you like to download and install the new components?"
LangString MyNewRel 2052 "检测到有效的更新内容，您是否希望立刻下载并安装最新内容？"
LangString MyDLFileList 1033 "Downloading file list..."
LangString MyDLFileList 2052 "下载文件列表..."
LangString MyDLFailed 1033 "Download failed: $TEMP1."
LangString MyDLFailed 2052 "更新失败: $TEMP1."
LangString MySuccess 1033 "Success."
LangString MySuccess 2052 "成功。"
LangString MyDLFailed2 1033 "Download failed: $TEMP2"
LangString MyDLFailed2 2052 "下载失败: $TEMP2"
LangString MyDecompFailed 1033 "Decompress failed: $PLUGINSDIR\$MODNAME.zip"
LangString MyDecompFailed 2052 "解压缩失败: $PLUGINSDIR\$MODNAME.zip"
LangString MyUpdateFailed 1033 "Directory in use.  Please quit all programs before update."
LangString MyUpdateFailed 2052 "目录或文件正被程序使用，更新前请关闭程序！"
LangString MyPostInstFailed 1033 "Post install failed: $INSTDIR\pkgs\$MODNAME\POSTINST.exe"
LangString MyPostInstFailed 2052 "安装或升级失败: $INSTDIR\pkgs\$MODNAME\POSTINST.exe"
LangString MyCurVer 1033 "Current Vers.: $MODREV My Vers.: $TEMP3"
LangString MyCurVer 2052 "最新版本.: $MODREV 当前版本.: $TEMP3"
LangString MyModule 1033 "module: $TEMP2"
LangString MyModule 2052 "模式: $TEMP2"
LangString DLdownloading 1033 "Downloading %s"
LangString DLdownloading 2052 "正在下载%s"
LangString DLconnecting 1033 "Connecting ..."
LangString DLconnecting 2052 "建立连接中..."
LangString DLsecond 1033 "second"
LangString DLsecond 2052 "秒钟"
LangString DLminute 1033 "minute"
LangString DLminute 2052 "分"
LangString DLhour 1033 "hour"
LangString DLhour 2052 "小时"
LangString DLplural 1033 "s"
LangString DLplural 2052 ""
LangString DLprogress 1033 "%dkB (%d%%) of %dkB @ %d.%01dkB/s"
LangString DLprogress 2052 "下载进度：%dkB (%d%%)  %dkB @ 速度：%d.%01dkB/s"
LangString DLremaining 1033 "(%d %s%s remaining)"
LangString DLremaining 2052 "(剩余%d %s%s)"


Section ""

  SetDetailsPrint both
  
  Call ConnectInternet

    ;Check for a new release
    
    !insertmacro MUI_HEADER_TEXT $(MyChkNew1) $(MyChkNew2)
    
    FileOpen $TEMP1 "$INSTDIR\VERSION" r
    FileRead $TEMP1 $MYVERSION
    FileClose $TEMP1
  
    Push $MYVERSION
    Call TrimNewLines
    Pop $MYVERSION
    
    DetailPrint $(MyVersTxt)
    DetailPrint ""
    
    DetailPrint $(MyCheckTxt)
    DetailPrint ""
    
    NSISdl::download_quiet "http://$SERVER/hr_update/entry?mtype=regDownload&HW_model=IQAHC&HW_rev=4096&Release_rev=$MYVERSION" "$PLUGINSDIR\Update"
    Pop $TEMP1
     
    StrCmp $TEMP1 "success" ReadVersion
      MessageBox MB_OK|MB_ICONSTOP $(MyDLFail)
      Call DoQuit
    
    ReadVersion:
    
    FileOpen $TEMP1 "$PLUGINSDIR\Update" r
    FileRead $TEMP1 $NEWVERSION
    StrCpy $NEWVERSION $NEWVERSION 16 14
    FileClose $TEMP1
    
    StrCmp $NEWVERSION "" "" +3
      MessageBox MB_OK|MB_ICONSTOP $(MyInvVers)
      Call DoQuit

    Push $NEWVERSION
    Call TrimNewLines
    Pop $NEWVERSION
      
    StrCmp $NEWVERSION $MYVERSION +3
      DetailPrint $(MyStaVers)
      Goto UpdateMsg
    
    DetailPrint $(MyNoRel)
    StrCmp $LAUNCHER "yes" "" +2
    Call DoQuit
    Goto Finish
    
    UpdateMsg:
    
    MessageBox MB_YESNO|MB_ICONQUESTION $(MyNewRel) IDNO Finish
    
    ;Close the App (files in use cannot be updated)
    Call CloseMenu

    DetailPrint $(MyDLFileList)

    NSISdl::download_quiet /TIMEOUT=30000 "http://$SERVER/hr_update/entry?mtype=extswDownload&HW_model=IQAHC&HW_rev=4096&Release_rev=$NEWVERSION" "$PLUGINSDIR\Update"
    Pop $TEMP1

    StrCmp $TEMP1 "success" +3
      MessageBox MB_OK|MB_ICONSTOP $(MyDLFailed)
      Call DoQuit

    DetailPrint $(MySuccess)
    FileOpen $TEMP1 "$PLUGINSDIR\Update" r

    Loop:
      FileRead $TEMP1 $TEMP2
      Push $TEMP2
      Call TrimNewLines
      Pop $TEMP2

      StrCmp $TEMP2 "" LoopDone

      StrCpy $TEMP3 $TEMP2 4
      StrCmp $TEMP3 "file" "" next1
        StrCmp $DODOWNLOAD "no" loop
        StrLen $TEMP3 $TEMP2
        IntOp $TEMP3 $TEMP3 - 11
        StrCpy $TEMP3 $TEMP2 "" $TEMP3
        StrCmp $TEMP3 "release.dsc" loop
        Push $TEMP2
        Call GetValueFromPair
        Pop $TEMP2
        NSISdl::download /TRANSLATE $(DLdownloading) $(DLconnecting) $(DLsecond) $(DLminute) $(DLhour) $(DLplural) $(DLprogress) $(DLremaining) /TIMEOUT=30000 $TEMP2 "$PLUGINSDIR\$MODNAME.zip"
        Pop $TEMP3
        StrCmp $TEMP3 "success" +3
          MessageBox MB_OK|MB_ICONSTOP $(MyDLFailed2)
          Call DoQuit
        !insertmacro ZIPDLL_EXTRACT "$PLUGINSDIR\$MODNAME.zip" "$INSTDIR\pkgs\$MODNAME.new" "<ALL>"
        Pop $TEMP3
        StrCmp $TEMP3 "success" +4
          MessageBox MB_OK|MB_ICONSTOP $(MyDecompFailed)
          RMDir /r "$INSTDIR\pkgs\$MODNAME.new"
          Call DoQuit
        ClearErrors
        IfFileExists "$INSTDIR\pkgs\$MODNAME.new\POSTINST.exe" "" +6
          ExecWait "$INSTDIR\pkgs\$MODNAME.new\POSTINST.exe"
          IfErrors "" +4
          MessageBox MB_OK|MB_ICONSTOP $(MyPostInstFailed)
          RMDir /r "$INSTDIR\pkgs\$MODNAME.new"
          Call DoQuit
        IfFileExists "$INSTDIR\pkgs\$MODNAME" "" +2
        Rename "$INSTDIR\pkgs\$MODNAME" "$INSTDIR\pkgs\$MODNAME.bak"
        Rename "$INSTDIR\pkgs\$MODNAME.new" "$INSTDIR\pkgs\$MODNAME"
	IfErrors "" +4
          MessageBox MB_OK|MB_ICONSTOP $(MyUpdateFailed)
          RMDir /r "$INSTDIR\pkgs\$MODNAME.new"
          Call DoQuit
        RMDir /r "$INSTDIR\pkgs\$MODNAME.bak"

      next1:
      StrCpy $TEMP3 $TEMP2 7
      StrCmp $TEMP3 "release" "" next2
        Push $TEMP2
        Call GetValueFromPair
        Pop $TEMP2
        StrCpy $MODREV $TEMP2
        FileOpen $TEMP2 "$INSTDIR\pkgs\$MODNAME\VERSION" r
        FileRead $TEMP2 $TEMP3
        FileClose $TEMP2
        Push $TEMP3
        Call TrimNewLines
        Pop $TEMP3
        DetailPrint $(MyCurVer)
        StrCmp "$MODREV" "$TEMP3" "" +3
          StrCpy $DODOWNLOAD "no"
          goto +2
          StrCpy $DODOWNLOAD "yes"

      next2:
      StrCpy $TEMP3 $TEMP2 7
      StrCmp $TEMP3 "act_key" "" next3
        Push $TEMP2
        Call GetValueFromPair
        Pop $TEMP2
        DetailPrint $(MyModule)
        StrCpy $MODNAME $TEMP2

      next3:
      Goto Loop

  LoopDone:
    FileClose $TEMP1
    FileOpen $TEMP2 "$INSTDIR\VERSION" w
    FileWrite $TEMP2 $NEWVERSION
    FileClose $TEMP2
  
  Finish:

SectionEnd

