;##############################################################
;### General product dependent constants
;##############################################################
#define SysDrive  GetEnv('SystemDrive')
#define ProdName  "crwdaq"
#define ExecFile  "crwdaq.exe"
#define ExecName  "\crwdaq\crwdaq.exe"
#define Product   "crwdaq for Windows"
#define ProdDir   "\opt\daqgroup\suite"
#define OutputID  "install-daqgroup-crwdaq"
#define OutputDir "\opt\daqgroup"
#define Publisher "DaqGroupTeam"
#define Contact   "mailto:daqgroup@mail.ru"
#define ProdURL   "http://www.crw-daq.su/"
#define Comments  "CrwDaq - data acquisition, process control and analysis system"
#define Release   SysDrive+ProdDir+"\crwdaq\release.txt"
#define License   SysDrive+ProdDir+"\crwdaq\license.md"
#define ProdIcon  SysDrive+ProdDir+"\crwdaq\crwdaq.ico"

;##############################################################
; Read crwdaq release version from the file \crwdaq\release.txt
;##############################################################
#define Version
#define FileHandle = FileOpen(Release)
#if FileHandle
  #define Version = FileRead(FileHandle)
  #expr Delete(Version,Pos('-',Version),Len(Version))
  #expr FileClose(FileHandle)
#endif

;##############################################################
;### General installer settings
;##############################################################
[Setup]
; NOTE: The value of AppId uniquely identifies this application.
; Do not use the same AppId value in installers for other applications.
; (To generate a new GUID, click Tools | Generate GUID inside the IDE.)
AppId={{D41386CF-0675-4283-A20F-6BAF66690267}
AppName={#ProdName}
AppVersion={#Version}
AppVerName={#ProdName} {#Version}
AppComments={#Comments}
AppPublisher={#Publisher}
AppPublisherURL={#Contact}
AppSupportURL={#Contact}
AppUpdatesURL={#ProdURL}
DefaultDirName={sd}{#ProdDir}
DisableDirPage=yes
DefaultGroupName={#ProdName}
DisableProgramGroupPage=yes
LicenseFile={#License}
OutputDir={#SysDrive}{#OutputDir}
OutputBaseFilename={#OutputID}
SetupIconFile={#ProdIcon}
Compression=lzma
SolidCompression=yes

;##############################################################
;### Available languages
;##############################################################
[Languages]
Name: "english"; MessagesFile: "compiler:Default.isl"
Name: "russian"; MessagesFile: "compiler:Languages\Russian.isl"

;##############################################################
;### Installation tasks
;##############################################################
[Tasks]
Name: "DeleteOldVersion"; Description: "Удалить старую версию"

;##############################################################
;### Installation files
;##############################################################
[Files]
Source: "{#SysDrive}{#ProdDir}\crwdaq\*"; DestDir: "{app}\crwdaq"; Flags: ignoreversion recursesubdirs createallsubdirs
Source: "{#SysDrive}{#ProdDir}\crwkit\*"; DestDir: "{app}\crwkit"; Flags: ignoreversion recursesubdirs createallsubdirs
Source: "{#SysDrive}{#ProdDir}\crwlib\*"; DestDir: "{app}\crwlib"; Flags: ignoreversion recursesubdirs createallsubdirs
Source: "{#SysDrive}{#ProdDir}\crwdaq\resource\launch\crwlnk\*"; DestDir: "{group}"; Flags: ignoreversion recursesubdirs createallsubdirs

;##############################################################
;### Create shortcuts in the Start Menu and/or other locations
;##############################################################
[Icons]
Name: "{group}\{cm:ProgramOnTheWeb,{#ProdName}}"; Filename: "{#ProdURL}"

;##############################################################
;### Set custom messages
;##############################################################
[Messages]
SetupWindowTitle=Setup {#ProdName} version {#Version}
BeveledLabel= {#Comments}

[CustomMessages]
english.ProgramOnTheWeb=Site {#ProdName}
russian.ProgramOnTheWeb=Сайт {#ProdName}

;##############################################################
;### Specifies programs to execute after successfully installed
;##############################################################
[Run]
Filename: "{app}\crwdaq\resource\shell\grun.exe"; Parameters: "-cwh rmdir /S /Q {app}.old"; WorkingDir: "{app}"; Flags: skipifdoesntexist runhidden; Description: "Удалить старую версию"; StatusMsg: "Удаление старой версии..."; Tasks: deleteoldversion; Check: IsInstalled

;##############################################################
;### Pascal script
;##############################################################
[Code]
const
  ec_Success   = 0; // Installation success
  ec_Installed = 1; // Already installed...
  ec_Aborted   = 2; // Installation aborted
  ec_Refused   = 3; // Installation refused
  RuQuietMessageError = 'Не могу удалить или переименовать каталог {#ProdDir}. Возможно, он заблокирован или нет прав доступа. Попробуйте разблокировать и повторите установку.';
  EnQuietMessageError = 'Could not delete or rename directory {#ProdDir}. Maybe it is locked or no access rights. Try to unlock files and repeat installation again.';

var
  SetupExitCode:Integer;

{
Multilanguage support
}
function RusEng(Rus,Eng:String):String;
begin
  Result:=Eng;
  if CompareText(ActiveLanguage, 'russian') = 0 then Result:=Rus;
end;

{
Usage: ExecTooltip('message','stdSuccess')
Execute unix fpquitip command
Example: ExecTooltip('text "Complete." preset stdSuccess')
}
function ExecTooltip(arg:String):Boolean;
var ErrorCode:Integer;
begin
  Result:=Exec(ExpandConstant('{cmd}'), '/c unix fpquitip '+arg, '', SW_HIDE, ewNoWait, ErrorCode);
end;

{
Usage: ShowTooltip('message','stdSuccess')
Execute ExecTooltip(arg) function (see above)
Example: ShowTooltip('Complete','stdSuccess')
}
function ShowTooltip(text,preset:String):Boolean;
var arg:String;
begin
  arg:=AddQuotes(GetDateTimeString('dd.mm.yyyy-hh:nn:ss: ', '.', ':')+text);
  arg:='text '+arg+' preset '+preset;
  Result:=ExecTooltip(arg);
end;

{
Program is installed detected
}
function IsInstalled:Boolean;
begin
  Result:=False;
  if FileExists('{#SysDrive}{#ProdDir}{#ExecName}') then Result:=True;
end;

{
Confirm installation: Silent/MsgBox=IDYES -> Refuse install
}
function InstallationConfirm(RuMessage,EnMessage:String; var ExitCode:Integer):Boolean;
begin
  Result:=False;
  if WizardSilent then begin
    ExitCode:=ec_Installed;
  end else begin
    if MsgBox(RusEng(RuMessage, EnMessage), mbConfirmation, MB_YESNO) = IDYES then begin
      ExitCode:=ec_Installed;
    end else begin
      Result:=True;
    end;
  end;
end;

{
Skip task page
}
function ShouldSkipPage(PageID:Integer):Boolean;
begin
  Result:=False;
  if not IsInstalled then begin
//     WizardSelectTasks('!DeleteOldVersion'); // It's not supported on Inno Setup version 5 and lower
                                               // Uncomment this line if InnoSetup version 6 and higher is used
    if PageID = wpSelectTasks then Result:=True;
  end;
end;

{
Main setup initialization
}
function InitializeSetup():Boolean;
var
  WasInstalledStr: AnsiString; 
  WasInstalled: Integer; 
  ToBeInstall: Integer;
  ReleaseFile: String;
begin
  Result:=True;
  ReleaseFile:='{#Release}' // Get release file name
  ToBeInstall:=StrToIntDef('{#Version}', 0); // Get version number to be install
  if IsInstalled then begin
    if FileExists(ReleaseFile) then begin
      if LoadStringFromFile(ReleaseFile, WasInstalledStr) then begin // Read crwdaq release version from the file: \crwdaq\release.txt
        Delete(WasInstalledStr, Pos('-', WasInstalledStr), Length(WasInstalledStr)); // Remove version time stamp
        WasInstalled:=StrToIntDef(WasInstalledStr, 0);
      end;
      if WasInstalled = ToBeInstall then Result:=InstallationConfirm('Пакет crwdaq версии '+WasInstalledStr+' уже установлен.'+ #13#13 +'Прервать установку?', \
                                                                     'crwdaq '+WasInstalledStr+' is already installed.'+ #13#13 +'Break installation?', SetupExitCode) else
      if WasInstalled > ToBeInstall then Result:=InstallationConfirm('Более новая версия пакета crwdaq ('+WasInstalledStr+') уже установлена.'+ #13#13 +'Прервать установку?', \
                                                                     'A newer version of crwdaq '+WasInstalledStr+' is already installed.'+ #13#13 +'Break installation?', SetupExitCode);
    end;
  end;
end;

function PrepareToInstall(var NeedsRestart:Boolean):String;
begin
  if DirExists('{#SysDrive}{#ProdDir}'+'.old') then begin
    DelTree('{#SysDrive}{#ProdDir}'+'.old', True, True, True);
  end;
  if DirExists(ExpandConstant('{group}')) then begin
    DelTree(ExpandConstant('{group}'), True, True, True);
  end;
  if IsInstalled then begin
    if not RenameFile('{#SysDrive}{#ProdDir}', '{#SysDrive}{#ProdDir}'+'.old') then begin
      Result:=RusEng(RuQuietMessageError, EnQuietMessageError);
      SetupExitCode:=ec_Refused;
    end else Result:='';
  end;
end;

procedure CancelButtonClick(PageID:Integer; var Cancel,Confirm:Boolean);
begin
  Confirm:=True;
  SetupExitCode:=ec_Aborted;
end;

procedure CurStepChanged(CurStep:TSetupStep);
begin
  if CurStep = ssDone then SetupExitCode:=ec_Success;
end;

function GetCustomSetupExitCode:Integer;
begin
 Result:=SetupExitCode;
end;

procedure DeinitializeSetup();
begin
  if GetCustomSetupExitCode = ec_Success then begin
    ShowTooltip('{#ProdName} installed successful.', 'stdSuccess');
  end else
  if GetCustomSetupExitCode = ec_Installed then begin
    ShowTooltip('{#ProdName} is already installed, installation skipped.', 'stdSuccess');
  end else
  if GetCustomSetupExitCode = ec_Aborted then begin
    ShowTooltip('{#ProdName} installation aborted. Try again later.', 'stdError');
  end else
  if GetCustomSetupExitCode = ec_Refused then begin
    ShowTooltip('{#ProdName} installation refused. Try again later.', 'stdError');
  end;
end;
