;##############################################################
;### General product dependent constants
;##############################################################
#define SysDrive  GetEnv('SystemDrive')
#define ProdName  "crwdaq"
#define ExecFile  "crwdaq.exe"
#define ExecName  "\crwdaq\crwdaq.exe"
#define Name      "crwdaq"
#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  "Data acquisition, process control and analysis system for Windows"
#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))
;   #define Version = Copy(Version,1,8);
  #expr FileClose(FileHandle)
#endif

[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
; Compression=zip
SolidCompression=yes

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

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

[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

[Icons]
Name: "{group}\{cm:ProgramOnTheWeb,{#Name}}"; Filename: "{#ProdURL}"

[Messages]
BeveledLabel= Setup CRW-DAQ version {#Version}
SetupWindowTitle=Setup - {#ProdName} version {#Version}

[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

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

[Code]
const
  ec_Success   = 0; // Installation success
  ec_Installed = 1; // Already installed...
  ec_InitFail  = 2; // Installation error..
  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.5.9 and lower
    if PageID = wpSelectTasks then Result:=True;
  end;
end;

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

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

procedure CancelButtonClick(PageID:Integer; var Cancel,Confirm:Boolean); 
begin
  Confirm:=true;
  if SetupExitCode<>ec_InitFail then SetupExitCode:=ec_Refused;
  if PageID=wpInstalling then SetupExitCode:=ec_InitFail;
end;

procedure CurStepChanged(CurStep:TSetupStep);
begin
  if CurStep=ssDone then
  if SetupExitCode<>ec_InitFail 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_InitFail 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;
