;##############################################################
;### General product dependent constants
;##############################################################
#define appid     "{4E1C9114-836A-4B9D-923C-42A0C384115F}"
#define SysDrive  GetEnv('SystemDrive')
#define Name      "fpcupdeluxe-x86"
#define Product   "fpcupdeluxe"
#define ProdName  "Lazarus_fpcupdeluxe"
#define ExecName  "\lazarus\lazarus.exe"
#define ProdDir   "\opt\daqgroup\development\tools\fpcupdeluxe"
#define OutputID  "install-daqgroup-fpcupdeluxe-x86"
#define OutputDir "\opt\daqgroup\development\tools\"
#define Publisher "DaqGroupTeam"
#define Contact   "mailto:daqgroup@mail.ru"
#define Comments  "Lazarus fpcupdeluxe build by DaqGroup team"
#define Version   GetDateTimeString('yyyymmdd', '', '')
#define ProdIcon  SysDrive+ProdDir+"\lazarus\images\icons\lazarus.ico"
#define EntireKey "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\"

;##############################################################
;### General installer settings
;##############################################################
[Setup]
AppId={{#appid}
AppName={#Product}
AppVersion={#Version}
AppVerName={#Product} {#Version}
AppPublisher={#Publisher}
AppPublisherURL={#Contact}
AppSupportURL={#Contact}
AppUpdatesURL={#Contact}
AppComments={#Comments}
DefaultDirName={sd}{#ProdDir}
DefaultGroupName={#ProdName}
DisableDirPage=yes
DisableProgramGroupPage=yes
OutputBaseFilename={#OutputID}
OutputDir={#SysDrive}{#OutputDir}
SetupIconFile={#ProdIcon}
Compression=lzma
SolidCompression=yes
UninstallDisplayName={#Product}
CreateUninstallRegKey=no

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

;##############################################################
;### Installation tasks
;##############################################################
[Tasks]
Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked
Name: "addregistry"; Description: "{cm:AddRegistryKey}";    GroupDescription: "{cm:AdditionalTasks}"; Flags: unchecked

;##############################################################
;### Installation files
;##############################################################
[Files]
Source: "{#SysDrive}{#ProdDir}\*"; Excludes: "unins???.*,.git*,lazarus.old.exe";  DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs

;##############################################################
;### Create shortcuts in the Start Menu and/or other locations
;##############################################################
[Icons]
Name: "{commonprograms}\{#Product}"; Filename: "{app}\{#Product}.lnk"
Name: "{commondesktop}\{#Product}";  Filename: "{app}\{#Product}.lnk"; Tasks: desktopicon

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

[CustomMessages]
english.AddRegistryKey=Add registry keys
russian.AddRegistryKey=Зарегистрировать в системном реестре
english.AdditionalTasks=Additional tasks:
russian.AdditionalTasks=Дополнительные задачи:

;##############################################################
;### Specifies programs to execute after successfully installed
;##############################################################
[Run]
Filename: "{cmd}"; Parameters: "/C rmdir /S /Q {app}.old"; WorkingDir: "{app}"; Flags: skipifdoesntexist runhidden; Description: "Удалить старую версию"; StatusMsg: "Удаление старой версии..."

;##############################################################
;### Defines any registry keys and values
;##############################################################
[Registry]
Root: HKLM; Subkey: "{#EntireKey}{#Name}"; Flags: uninsdeletekey; Tasks: addregistry
Root: HKLM; Subkey: "{#EntireKey}{#Name}"; ValueType: string; ValueName: "Comments";        ValueData: "{#Comments}";    Flags: uninsdeletekey; Tasks: addregistry
Root: HKLM; Subkey: "{#EntireKey}{#Name}"; ValueType: string; ValueName: "DisplayName";     ValueData: "{#Name}";        Flags: uninsdeletekey; Tasks: addregistry
Root: HKLM; Subkey: "{#EntireKey}{#Name}"; ValueType: string; ValueName: "UninstallString"; ValueData: "{uninstallexe}"; Flags: uninsdeletekey; Tasks: addregistry
Root: HKLM; Subkey: "{#EntireKey}{#Name}"; ValueType: string; ValueName: "DisplayIcon";     ValueData: "{#ProdIcon}";    Flags: uninsdeletekey; Tasks: addregistry
Root: HKLM; Subkey: "{#EntireKey}{#Name}"; ValueType: string; ValueName: "Publisher";       ValueData: "{#Publisher}";   Flags: uninsdeletekey; Tasks: addregistry
Root: HKLM; Subkey: "{#EntireKey}{#Name}"; ValueType: string; ValueName: "DisplayVersion";  ValueData: "{#Version}";     Flags: uninsdeletekey; Tasks: addregistry
Root: HKLM; Subkey: "{#EntireKey}{#Name}"; ValueType: string; ValueName: "Contact";         ValueData: "{#Contact}";     Flags: uninsdeletekey; Tasks: addregistry

;##############################################################
;### 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;

{
Main setup initialization
}
function InitializeSetup():Boolean;
var
  WasInstalledStr: AnsiString;
  WasInstalled: Integer;
  ToBeInstall: Integer;
  Uninstaller: String;
  ErrorCode: Integer;
begin
  Result:=True;
  ToBeInstall:=StrToIntDef('{#Version}', 0);
  if IsInstalled then begin
    if RegKeyExists(HKEY_LOCAL_MACHINE, 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{#Name}') then begin
      RegQueryStringValue(HKEY_LOCAL_MACHINE, 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{#Name}', 'DisplayVersion', WasInstalledStr);
      WasInstalled:=StrToIntDef(WasInstalledStr, 0);
      if WasInstalled = ToBeInstall
      then Result:=InstallationConfirm('{#ProdName} уже установлен.'+ #13#13 +'Если вы продолжите, установленная сборка будет удалена!'+ #13#13 +'Прервать установку?', \
                                       '{#ProdName} is already installed.'+ #13#13 +'If you want to continue, current build will be delete!'+ #13#13 +'Break installation?', SetupExitCode)
      else if WasInstalled > ToBeInstall
      then Result:=InstallationConfirm('Более новая версия {#ProdName} уже установлена.'+ #13#13 +'Если вы продолжите, установленная сборка будет удалена!'+ #13#13 +'Прервать установку?', \
                                       'A newer version of {#ProdName} is already installed.'+ #13#13 +'If you want to continue, current build will be delete!'+ #13#13 +'Break installation?', SetupExitCode);
      if Result = True then begin
        RegQueryStringValue(HKEY_LOCAL_MACHINE, 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{#Name}', 'UninstallString', Uninstaller);
        if FileExists(Uninstaller) then Exec(Uninstaller, '/SILENT', '', SW_SHOW, ewWaitUntilTerminated, ErrorCode);
      end;
    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 FileExists(ExpandConstant('{commonprograms}\{#Product}.lnk')) then begin
    DeleteFile(ExpandConstant('{commonprograms}\{#Product}.lnk'));
  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
  if SetupExitCode <> ec_Refused 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;
