#ifndef AppVersion
  #define AppVersion "0.1.0-experimental.10"
#endif
#ifndef SourceRoot
  #error SourceRoot must point at the self-contained Companion publish directory.
#endif
#ifndef OutputRoot
  #error OutputRoot must point at the installer output directory.
#endif

[Setup]
AppId={{EDEB45E4-41CB-4D7A-A479-4073A1A08B93}
AppName=Lumi Companion
AppVersion={#AppVersion}
AppVerName=Lumi Companion {#AppVersion}
AppPublisher=Lumi
DefaultDirName={localappdata}\Programs\Lumi Companion
DefaultGroupName=Lumi Companion
DisableProgramGroupPage=yes
PrivilegesRequired=lowest
ArchitecturesAllowed=x64compatible
ArchitecturesInstallIn64BitMode=x64compatible
OutputDir={#OutputRoot}
OutputBaseFilename=Lumi.Companion-Setup
Compression=lzma2/ultra64
SolidCompression=yes
WizardStyle=modern
SetupLogging=yes
CloseApplications=yes
CloseApplicationsFilter=Lumi.Companion.App.exe
RestartApplications=no
UninstallDisplayName=Lumi Companion
UninstallDisplayIcon={app}\Lumi.Companion.App.exe
VersionInfoDescription=Lumi Companion installer
VersionInfoProductName=Lumi Companion
VersionInfoProductTextVersion={#AppVersion}

[Files]
Source: "{#SourceRoot}\Lumi.Companion.App.exe"; DestDir: "{app}"; Flags: ignoreversion
Source: "{#SourceRoot}\components\*"; DestDir: "{app}\components"; Flags: ignoreversion recursesubdirs createallsubdirs

[Icons]
Name: "{autoprograms}\Lumi Companion"; Filename: "{app}\Lumi.Companion.App.exe"

[Run]
Filename: "{app}\Lumi.Companion.App.exe"; Description: "Open Lumi Companion"; Flags: nowait postinstall skipifsilent

[Code]
procedure ImportPairingPackage;
var
  FindRec: TFindRec;
  SourcePath: String;
  TargetPath: String;
begin
  { Portable and installed builds share the same DPAPI credential directory. Do
    not create another authorized device merely because an existing user moves
    the executable into its durable installed location. }
  if FileExists(ExpandConstant('{localappdata}\Lumi\Companion\device.credential')) then
    Exit;
  if FindFirst(ExpandConstant('{src}\*.lumi-pairing.json'), FindRec) then
  begin
    try
      SourcePath := AddBackslash(ExpandConstant('{src}')) + FindRec.Name;
      TargetPath := AddBackslash(ExpandConstant('{app}')) + FindRec.Name;
      if not CopyFile(SourcePath, TargetPath, False) then
        MsgBox('Lumi Companion was installed, but its one-time pairing package could not be imported. Open Companion and choose the pairing file manually.', mbError, MB_OK);
    finally
      FindClose(FindRec);
    end;
  end;
end;

procedure CurStepChanged(CurStep: TSetupStep);
begin
  if CurStep = ssPostInstall then
    ImportPairingPackage;
end;
