#define ExteorName 'Экстеор 4.9'
#define ExteorEXE 'Exteor.exe'
#define Platform 'x64'
#define UpdateURL 'https://drive.google.com/open?id=1IJt25ZRQ-ZMA6t7hOqmo5cv05WJCQKMv&usp=drive_fs'
#define ExteorVersion() GetVersionNumbersString('..\bin\' + Platform + '\Exteor.exe')
   
#define ConceptDomain 'CONCEPT'
#define ExteorAppID '{EB3E39CA-7B66-42B3-8688-FE56D4BB0B23}'
#define PythonVer '3.12.2'
#define PythonRedist 'python-'  + PythonVer + '-amd64.exe'
#define PythonDownload 'https://www.python.org/ftp/python/' + PythonVer + '/' + PythonRedist
#define VSRedist 'VC_redist.' + Platform + '.exe'
#define VSDownload 'https://aka.ms/vs/17/release/' + VSRedist

#define RK_Python3 'SOFTWARE\Python\PythonCore\3.12\InstallPath'
#define RK_PyPath 'PyPath312_64'
#define RK_VCRedistr 'SOFTWARE\WOW6432Node\Microsoft\VisualStudio\14.0\VC\Runtimes\' + Platform
 
#define RK_Exteor 'SOFTWARE\CIHT Concept\Экстеор 4.9'
#define RK_ExteorUninstall 'SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\{EB3E39CA-7B66-42B3-8688-FE56D4BB0B23}_is1'

[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 = {{#ExteorAppID}

AppName = {#ExteorName}
AppVersion = {#ExteorVersion}
AppVerName = {#ExteorName}
VersionInfoVersion = {#ExteorVersion}
AppPublisher = НП ЦИВТ КОНЦЕПТ
AppPublisherURL = http://www.acconcept.ru/
AppSupportURL = bugreport@acconcept.ru
AppUpdatesURL = {#UpdateURL}

DefaultDirName = {autopf64}\CIHT Concept\{#ExteorName}
DefaultGroupName = {#ExteorName}

LicenseFile = ..\distr\app\Документация\Лицензионное соглашение.rtf
SetupIconFile = ..\resource\ExteorApp.ico

SourceDir = ..\distr

OutputDir = ..\bin\{#Platform}
OutputBaseFilename = ExteorSetup

AllowNoIcons = yes
ChangesAssociations = yes

UninstallDisplayIcon={app}\{#ExteorEXE}

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

[Tasks]
Name: desktopicon; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"
Name: quicklaunchicon; Description: "{cm:CreateQuickLaunchIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked

[Files]
Source: "..\bin\x64\Exteor.exe"; DestDir: "{app}"; Flags: ignoreversion
Source: "..\import\cctext\*"; DestDir: "{app}\cctext"; Flags: ignoreversion
Source: "app\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs
Source: "..\distr\app\DejaVu Sans.ttf"; DestDir: "{app}"; Flags: ignoreversion

Source: "..\script\PymorphyInstall.bat"; DestDir: {tmp}; Flags: deleteafterinstall

[Icons]
Name: "{group}\{#ExteorName}"; Filename: "{app}\{#ExteorEXE}"
Name: "{group}\{cm:UninstallProgram,{#ExteorName}}"; Filename: "{uninstallexe}"
Name: "{autodesktop}\{#ExteorName}"; Filename: "{app}\{#ExteorEXE}"; Tasks: desktopicon
Name: "{autodesktop}\Экстеор - Текущая версия"; Filename: "{app}\Экстеор - Текущая версия.lnk"; Tasks: desktopicon; Check: IsConceptDomain
Name: "{autoappdata}\Microsoft\Internet Explorer\Quick Launch\{#ExteorName}"; Filename: "{app}\{#ExteorEXE}"; WorkingDir: {app}; Tasks: quicklaunchicon

[CustomMessages]
russian.NewerVersionExists = Более поздняя версия {#ExteorName} уже установлена. %n%nУстанавливаемая версия: {#ExteorVersion}%nТекущая версия: 
russian.SameVersionExists = На компьютере уже установлен {#ExteorName} версия {#ExteorVersion}.%n%nХотите переустановить программу?
russian.ReadMe = Ознакомиться с ReadMe
russian.CppRedist = Установка Visual C++ Redistributable...
russian.PythonInstall = Установка Python 3.12...

[Registry]
Root: HKCR; Subkey: ".oss"; ValueType: string; ValueName: ""; ValueData: "OSS File"; Flags: uninsdeletevalue
Root: HKCR; Subkey: "OSS File"; ValueType: string; ValueName: ""; ValueData: "Операционная схема синтеза"; Flags: uninsdeletekey
Root: HKCR; Subkey: "OSS File\DefaultIcon"; ValueType: string; ValueName: ""; ValueData: "{app}\Exteor.exe,3"
Root: HKCR; Subkey: "OSS File\shell\open\command"; ValueType: string; ValueName: ""; ValueData: """{app}\Exteor.EXE"" ""%1"""

Root: HKCR; Subkey: ".rsm"; ValueType: string; ValueName: ""; ValueData: "RSM File"; Flags: uninsdeletevalue
Root: HKCR; Subkey: "RSM File"; ValueType: string; ValueName: ""; ValueData: "Модель РС-формы"; Flags: uninsdeletekey
Root: HKCR; Subkey: "RSM File\DefaultIcon"; ValueType: string; ValueName: ""; ValueData: "{app}\Exteor.exe,2"
Root: HKCR; Subkey: "RSM File\shell\open\command"; ValueType: string; ValueName: ""; ValueData: """{app}\Exteor.EXE"" ""%1"""

Root: HKCR; Subkey: ".trs"; ValueType: string; ValueName: ""; ValueData: "TRS File"; Flags: uninsdeletevalue
Root: HKCR; Subkey: "TRS File"; ValueType: string; ValueName: ""; ValueData: "Файл РС-формы КС"; Flags: uninsdeletekey
Root: HKCR; Subkey: "TRS File\DefaultIcon"; ValueType: string; ValueName: ""; ValueData: "{app}\Exteor.exe,1"
Root: HKCR; Subkey: "TRS File\shell\open\command"; ValueType: string; ValueName: ""; ValueData: """{app}\Exteor.EXE"" ""%1"""

[Run]
Filename: "{app}\{#ExteorEXE}"; Description: "{cm:LaunchProgram,{#StringChange(ExteorName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent
Filename: "{app}\Документация\README.rtf"; Description: "{cm:ReadMe}"; Flags: nowait postinstall skipifsilent unchecked shellexec
Filename: "{tmp}\{#VSRedist}"; Parameters: "/install /quiet /NORESTART"; StatusMsg: {cm:CppRedist}; Check: VCRedistNeedsInstall()
Filename: "{tmp}\{#PythonRedist}"; Parameters: "/quiet InstallAllUsers=1 PrependPath=1 Include_test=0"; StatusMsg: {cm:PythonInstall}; Check: PythonNeedsInstall() 
Filename: "{tmp}\PymorphyInstall.bat"; Parameters: """{code:PythonPath}"""

[Code]
function IsPythonMissing: Boolean; forward;
function GetPythonInstallPath: String; forward;
function VCRedistNeedsInstall: Boolean; forward;
function GetExteorInstalledVersion: String; forward;
function DownloadFile(url_from: String; fileName: String): Boolean; forward;

function InitializeSetup: Boolean;
var
  installedVersion: String;
  comparison: Integer;
begin
  installedVersion := GetExteorInstalledVersion
  if installedVersion = '' then begin
    Result := True
    exit
  end;
  comparison := CompareText(installedVersion,'{#ExteorVersion}')
  if comparison = 0 then
    Result := MsgBox(ExpandConstant('{cm:SameVersionExists}'), mbConfirmation, MB_YESNO) = IDYES
  else begin
    Result := comparison <= 0 
    if not Result then
      MsgBox(ExpandConstant('{cm:NewerVersionExists}') + installedVersion, mbInformation, MB_OK);
  end
end;

function GetExteorInstalledVersion: String;
begin
  if not RegQueryStringValue(HKEY_LOCAL_MACHINE,'{#RK_ExteorUninstall}', 'DisplayVersion', Result) then
    Result := ''
end;

function IsConceptDomain: Boolean;
begin
  Result := GetEnv('UserDomain') = '{#ConceptDomain}'
end;

function PythonNeedsInstall: Boolean;
begin
  Result := IsPythonMissing;
  if Result then
    Result := DownloadFile('{#PythonDownload}', '{#PythonRedist}')
end;

function PythonRegistryExists: Boolean;
begin
  Result := RegValueExists(HKLM64, '{#RK_Python3}', '');
end;

function GetPythonInstallPath: String;
begin
  Result := '';
  if PythonRegistryExists then
    RegQueryStringValue(HKLM64, '{#RK_Python3}', '', Result);
end;

function IsPythonMissing: Boolean;
var
  python: String;
begin
  python := GetPythonInstallPath;
  Result := python = '';
  if not Result then
    Result := not FileExists(python + 'python312.dll') or not FileExists(python + 'Scripts\pip.exe');
end;

function VCRedistNeedsInstall(): Boolean;
begin
  Result := not RegValueExists(HKLM64, '{#RK_VCRedistr}', 'Version');
  if Result then
    Result := DownloadFile('{#VSDownload}', '{#VSRedist}')
end;

function DownloadFile(url_from: String; fileName: String): Boolean;
begin
  try
    DownloadTemporaryFile(url_from, fileName, '', nil);
    Result := True;
  except
    Log(GetExceptionMessage);
    Result := False;
  end;
end;

function PythonPath(dummyValue: String): String;
begin
  Result := GetPythonInstallPath
end;

procedure DeinitializeSetup();
var
  python: String;
  destination: String;
begin
  python := GetPythonInstallPath + 'python312.dll';
  destination := ExpandConstant('{app}\python312.dll')
  if FileExists(python) then
    FileCopy(python, destination, False);
end;
