#define MyAppName "IT Nexus Agent"
#define MyAppVersion "1.2.4"
#define MyAppPublisher "Cereda Systems GmbH"
#define MyAppURL "https://it-nexus.cereda-systems.de"
#define MyAppExeName "it-nexus-agent.ps1"
#define InstallDir "{commonappdata}\IT Nexus Agent"

[Setup]
AppId={{B3F7A2C1-4E8D-4F2A-9B1C-7D3E5F6A8B2C}
AppName={#MyAppName}
AppVersion={#MyAppVersion}
AppPublisher={#MyAppPublisher}
AppPublisherURL={#MyAppURL}
DefaultDirName={#InstallDir}
DisableDirPage=yes
DefaultGroupName={#MyAppName}
DisableProgramGroupPage=yes
OutputDir=..\dist
OutputBaseFilename=IT-Nexus-Agent-Setup-v{#MyAppVersion}
SetupIconFile=
Compression=lzma2/ultra64
SolidCompression=yes
WizardStyle=modern
WizardSizePercent=120
PrivilegesRequired=admin
UninstallDisplayName={#MyAppName}
UninstallDisplayIcon={app}\it-nexus-agent.ps1
CloseApplications=no
DisableWelcomePage=no
WizardImageFile=compiler:WizModernImage.bmp
WizardSmallImageFile=compiler:WizModernSmallImage.bmp

[Languages]
Name: "german"; MessagesFile: "compiler:Languages\German.isl"

[Files]
Source: "it-nexus-agent.ps1"; DestDir: "{app}"; Flags: ignoreversion
Source: "config.json.template"; DestDir: "{app}"; DestName: "config.json"; Flags: ignoreversion onlyifdoesntexist

[Run]
Filename: "powershell.exe"; Parameters: "-ExecutionPolicy Bypass -NonInteractive -Command ""Unregister-ScheduledTask -TaskName 'IT Nexus Agent' -Confirm:$false -ErrorAction SilentlyContinue; $a = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-ExecutionPolicy Bypass -NonInteractive -WindowStyle Hidden -File \""{app}\it-nexus-agent.ps1\""'; $t = New-ScheduledTaskTrigger -RepetitionInterval (New-TimeSpan -Minutes 1) -Once -At (Get-Date); $s = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Minutes 2) -MultipleInstances IgnoreNew -StartWhenAvailable; $p = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest; Register-ScheduledTask -TaskName 'IT Nexus Agent' -Action $a -Trigger $t -Settings $s -Principal $p -Force; Start-ScheduledTask -TaskName 'IT Nexus Agent'"""; Flags: runhidden waituntilterminated; StatusMsg: "Registriere Windows Scheduled Task..."

[UninstallRun]
Filename: "powershell.exe"; Parameters: "-ExecutionPolicy Bypass -NonInteractive -Command ""Unregister-ScheduledTask -TaskName 'IT Nexus Agent' -Confirm:$false -ErrorAction SilentlyContinue"""; Flags: runhidden waituntilterminated

[Code]
var
  ServerUrlPage: TInputQueryWizardPage;
  AgentKeyPage: TInputQueryWizardPage;

procedure InitializeWizard;
begin
  ServerUrlPage := CreateInputQueryPage(wpWelcome,
    'Server-Konfiguration',
    'Gib die IT Nexus Server-Adresse ein.',
    '');
  ServerUrlPage.Add('Server URL:', False);
  ServerUrlPage.Values[0] := 'https://it-nexus.cereda-systems.de';

  AgentKeyPage := CreateInputQueryPage(ServerUrlPage.ID,
    'API Key',
    'Gib den Agent API Key ein. Diesen findest du in den IT Nexus Einstellungen.',
    '');
  AgentKeyPage.Add('Agent API Key:', False);
  AgentKeyPage.Values[0] := 'itx-4CPJPTHmCfdrL9D62WacCATEvuvULXcp7ECMpSaNUjsS344F6_L4Ug';
end;

function NextButtonClick(CurPageID: Integer): Boolean;
begin
  Result := True;
  if CurPageID = ServerUrlPage.ID then begin
    if ServerUrlPage.Values[0] = '' then begin
      MsgBox('Bitte gib eine Server URL ein.', mbError, MB_OK);
      Result := False;
    end;
  end;
  if CurPageID = AgentKeyPage.ID then begin
    if AgentKeyPage.Values[0] = '' then begin
      MsgBox('Bitte gib einen API Key ein.', mbError, MB_OK);
      Result := False;
    end;
  end;
end;

procedure CurStepChanged(CurStep: TSetupStep);
var
  ConfigFile: string;
  Config: TStringList;
begin
  if CurStep = ssPostInstall then begin
    ConfigFile := ExpandConstant('{app}\config.json');
    Config := TStringList.Create;
    try
      Config.Add('{');
      Config.Add('  "server_url": "' + ServerUrlPage.Values[0] + '",');
      Config.Add('  "agent_key": "' + AgentKeyPage.Values[0] + '"');
      Config.Add('}');
      Config.SaveToFile(ConfigFile);
    finally
      Config.Free;
    end;
  end;
end;
