Skip to content

A modern, self-hosted backup solution for secure, encrypted backups across local and cloud storage.

16.3 KB
Raw Blame
; Script generated by GitHub Copilot
; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES!

#define MyAppName "Pluton"
#define MyAppVersion "0.0.1"
#define MyAppPublisher "Amplebyte LLC"
#define MyAppURL "https://usepluton.com"
#define MyAppExeName "pluton.exe"
#define MyAppServiceName "Pluton"

[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={{F7A3B8C1-5D2E-4F6A-9B8C-1E2D3F4A5B6C}
AppName={#MyAppName}
AppVersion={#MyAppVersion}
;AppVerName={#MyAppName} {#MyAppVersion}
AppPublisher={#MyAppPublisher}
AppPublisherURL={#MyAppURL}
AppSupportURL={#MyAppURL}
AppUpdatesURL={#MyAppURL}
DefaultDirName={autopf}\{#MyAppName}
DefaultGroupName={#MyAppName}
DisableProgramGroupPage=yes
DisableWelcomePage=no
LicenseFile=..\..\dist\executables\pluton-win-x64\LICENSE
; Uncomment the following line to run in non administrative install mode (install for current user only.)
;PrivilegesRequired=lowest
PrivilegesRequired=admin
ArchitecturesInstallIn64BitMode=x64compatible
OutputDir=..\..\dist\installers
OutputBaseFilename=pluton-setup
Compression=lzma
SolidCompression=yes
WizardStyle=modern
WizardImageFile=sidebar.png
SetupIconFile=setup.ico

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

[Dirs]
; Create the data directory structure in ProgramData
; Restrict access to SYSTEM and Administrators only for sensitive data
Name: "{commonappdata}\{#MyAppName}"; Permissions: admins-full
Name: "{commonappdata}\{#MyAppName}\config"; Permissions: admins-full
Name: "{commonappdata}\{#MyAppName}\db"; Permissions: admins-full
Name: "{commonappdata}\{#MyAppName}\logs"; Permissions: admins-full
Name: "{commonappdata}\{#MyAppName}\backups"; Permissions: admins-full
Name: "{commonappdata}\{#MyAppName}\restores"; Permissions: admins-full
Name: "{commonappdata}\{#MyAppName}\temp"; Permissions: admins-full

[Files]
; Main executable
Source: "..\..\dist\executables\pluton-win-x64\{#MyAppExeName}"; DestDir: "{app}"; Flags: ignoreversion

; Documentation
Source: "..\..\dist\executables\pluton-win-x64\LICENSE"; DestDir: "{app}"; Flags: ignoreversion
Source: "..\..\dist\executables\pluton-win-x64\README.md"; DestDir: "{app}"; Flags: ignoreversion

; Binaries (restic, rclone) - Preserve directory structure
Source: "..\..\dist\executables\pluton-win-x64\binaries\*"; DestDir: "{app}\binaries"; Flags: ignoreversion recursesubdirs createallsubdirs

; Native modules (better-sqlite3) - Preserve directory structure
Source: "..\..\dist\executables\pluton-win-x64\node_modules\*"; DestDir: "{app}\node_modules"; Flags: ignoreversion recursesubdirs createallsubdirs

; Database Migrations (Required for app startup)
Source: "..\..\dist\executables\pluton-win-x64\drizzle\*"; DestDir: "{app}\drizzle"; Flags: ignoreversion recursesubdirs createallsubdirs skipifsourcedoesntexist

; NSSM for service management (Assumes you have downloaded nssm.exe to installers/windows/tools/)
Source: "tools\nssm.exe"; DestDir: "{app}"; Flags: ignoreversion

; Visual C++ Redistributable (required for native Node.js modules like better-sqlite3)
; Download from: https://aka.ms/vs/17/release/vc_redist.x64.exe
Source: "tools\vc_redist.x64.exe"; DestDir: "{tmp}"; Flags: ignoreversion deleteafterinstall; Check: not IsVCRedistInstalled

; Application icon for shortcuts
Source: "setup.ico"; DestDir: "{app}"; DestName: "pluton.ico"; Flags: ignoreversion

[Icons]
; Desktop shortcut to open Pluton in browser
Name: "{commondesktop}\Pluton"; Filename: "{app}\pluton-open.url"; IconFilename: "{app}\pluton.ico"; Comment: "Open Pluton Backup Dashboard"
; Start Menu shortcuts
Name: "{group}\Pluton"; Filename: "{app}\pluton-open.url"; IconFilename: "{app}\pluton.ico"; Comment: "Open Pluton Backup Dashboard"
Name: "{group}\Uninstall Pluton"; Filename: "{uninstallexe}"

[Registry]
; Set the data directory environment variable
Root: HKLM; Subkey: "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"; ValueType: string; ValueName: "PLUTON_DATA_DIR"; ValueData: "{commonappdata}\{#MyAppName}"; Flags: uninsdeletevalue


[Run]
; Install Visual C++ Redistributable if not already installed (required for native Node.js modules)
Filename: "{tmp}\vc_redist.x64.exe"; Parameters: "/install /quiet /norestart"; StatusMsg: "Installing Visual C++ Redistributable..."; Flags: waituntilterminated; Check: not IsVCRedistInstalled

; Install the service using NSSM (will fail silently if service already exists on upgrade - that's OK)
Filename: "{app}\nssm.exe"; Parameters: "install {#MyAppServiceName} ""{app}\{#MyAppExeName}"""; Flags: runhidden; StatusMsg: "Installing service..."
; Set service description
Filename: "{app}\nssm.exe"; Parameters: "set {#MyAppServiceName} Description ""Pluton Backup Service"""; Flags: runhidden
; Set service startup to automatic
Filename: "{app}\nssm.exe"; Parameters: "set {#MyAppServiceName} Start SERVICE_AUTO_START"; Flags: runhidden
; Set service AppDirectory
Filename: "{app}\nssm.exe"; Parameters: "set {#MyAppServiceName} AppDirectory ""{app}"""; Flags: runhidden
; Set environment variables for data directory on the service
Filename: "{app}\nssm.exe"; Parameters: "set {#MyAppServiceName} AppEnvironmentExtra PLUTON_DATA_DIR=""{commonappdata}\{#MyAppName}"""; Flags: runhidden
; Exit code 0 is a deliberate stop (e.g. port already in use) - do not restart
Filename: "{app}\nssm.exe"; Parameters: "set {#MyAppServiceName} AppExit 0 Exit"; Flags: runhidden
; Set stdout and stderr logging
Filename: "{app}\nssm.exe"; Parameters: "set {#MyAppServiceName} AppStdout ""{commonappdata}\{#MyAppName}\logs\service-out.log"""; Flags: runhidden
Filename: "{app}\nssm.exe"; Parameters: "set {#MyAppServiceName} AppStderr ""{commonappdata}\{#MyAppName}\logs\service-err.log"""; Flags: runhidden
; Harden data directory ACL: remove inherited permissions, grant SYSTEM and Administrators only
Filename: "icacls.exe"; Parameters: """{commonappdata}\{#MyAppName}"" /inheritance:r /grant:r *S-1-5-18:(OI)(CI)F /grant:r *S-1-5-32-544:(OI)(CI)F"; Flags: runhidden; StatusMsg: "Setting data directory permissions..."
; Start the service (BeforeInstall writes config.json + URL shortcut before the service launches)
Filename: "{app}\nssm.exe"; Parameters: "start {#MyAppServiceName}"; BeforeInstall: WriteConfigAndUrlFiles; Flags: runhidden; StatusMsg: "Starting service..."

[UninstallRun]
; Stop the service
Filename: "{app}\nssm.exe"; Parameters: "stop {#MyAppServiceName}"; Flags: runhidden; RunOnceId: "StopService"
; Remove the service
Filename: "{app}\nssm.exe"; Parameters: "remove {#MyAppServiceName} confirm"; Flags: runhidden; RunOnceId: "RemoveService"

[UninstallDelete]
; Remove dynamically created files
Type: files; Name: "{app}\pluton-open.url"

[Code]
var
  DashboardLinkLabel: TNewStaticText;
  FinishNoteLabel: TNewStaticText;
  SettingsPage: TInputQueryWizardPage;
  IsUpgrade: Boolean;
  
  // Variables to store inputs
  ServerPort, MaxConcurrentBackups: string;

// Check if Visual C++ Redistributable 2015-2022 (x64) is installed
// Required for native Node.js modules compiled with MSVC (e.g., @napi-rs/keyring)
function IsVCRedistInstalled: Boolean;
var
  Version: String;
begin
  Result := False;
  // Check for VC++ 2015-2022 Redistributable (x64) - version 14.x
  // The minimum version we need is 14.0 (VS 2015), but newer versions are backward compatible
  if RegQueryStringValue(HKLM, 'SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\x64', 'Version', Version) then
  begin
    Log('VC++ Redistributable found: ' + Version);
    Result := True;
  end
  else if RegQueryStringValue(HKLM, 'SOFTWARE\WOW6432Node\Microsoft\VisualStudio\14.0\VC\Runtimes\x64', 'Version', Version) then
  begin
    Log('VC++ Redistributable found (WOW6432Node): ' + Version);
    Result := True;
  end
  else
  begin
    Log('VC++ Redistributable not found - will install');
  end;
end;

// Check if service exists by querying its status
function ServiceExists(ServiceName: String): Boolean;
var
  ResultCode: Integer;
begin
  // Use sc query - returns 0 if service exists, non-zero otherwise
  Result := Exec('sc.exe', 'query "' + ServiceName + '"', '', SW_HIDE, ewWaitUntilTerminated, ResultCode) and (ResultCode = 0);
end;

// Check if config file exists (indicates existing installation)
function ConfigExists(): Boolean;
begin
  Result := FileExists(ExpandConstant('{commonappdata}\{#MyAppName}\config\config.json'));
end;

// Read port from existing config file (simple parsing)
function ReadPortFromConfig(): String;
var
  ConfigContent: AnsiString;
  ConfigPath: String;
  PortPos, PortEnd: Integer;
  PortStr: String;
begin
  Result := '5173'; // Default
  ConfigPath := ExpandConstant('{commonappdata}\{#MyAppName}\config\config.json');
  
  if LoadStringFromFile(ConfigPath, ConfigContent) then
  begin
    // Find "SERVER_PORT": and extract the number
    PortPos := Pos('"SERVER_PORT":', String(ConfigContent));
    if PortPos > 0 then
    begin
      PortStr := Copy(String(ConfigContent), PortPos + 14, 10); // Get chars after "SERVER_PORT":
      // Trim whitespace and extract number
      PortStr := Trim(PortStr);
      PortEnd := 1;
      while (PortEnd <= Length(PortStr)) and (PortStr[PortEnd] >= '0') and (PortStr[PortEnd] <= '9') do
        PortEnd := PortEnd + 1;
      if PortEnd > 1 then
        Result := Copy(PortStr, 1, PortEnd - 1);
    end;
  end;
end;

function GetDashboardUrl(): String;
begin
  if ServerPort = '' then
    ServerPort := '5173';

  Result := 'http://localhost:' + ServerPort;
end;

procedure DashboardLinkLabelOnClick(Sender: TObject);
var
  ErrorCode: Integer;
begin
  if not ShellExec('open', GetDashboardUrl(), '', '', SW_SHOWNORMAL, ewNoWait, ErrorCode) then
    MsgBox('Failed to open the dashboard URL.', mbError, MB_OK);
end;

// Stop the service if it's running
function StopService(ServiceName: String): Boolean;
var
  ResultCode: Integer;
begin
  Result := True;
  // Use net stop since nssm.exe might not be installed yet
  Exec('net', 'stop "' + ServiceName + '"', '', SW_HIDE, ewWaitUntilTerminated, ResultCode);
  // Give the service time to stop
  Sleep(2000);
end;

// Install service using NSSM
function InstallService(): Boolean;
var
  ResultCode: Integer;
  NssmPath, ExePath: String;
begin
  NssmPath := ExpandConstant('{app}\nssm.exe');
  ExePath := ExpandConstant('{app}\{#MyAppExeName}');
  Result := Exec(NssmPath, 'install "{#MyAppServiceName}" "' + ExePath + '"', '', SW_HIDE, ewWaitUntilTerminated, ResultCode);
end;

// Called at very start - detect upgrade early
function InitializeSetup(): Boolean;
begin
  Result := True;
  // Detect upgrade by checking if service or config exists
  IsUpgrade := ServiceExists('{#MyAppServiceName}') or ConfigExists();
  
  if IsUpgrade then
  begin
    // Read existing port for use throughout setup
    ServerPort := ReadPortFromConfig();
    MaxConcurrentBackups := '2'; // Default, not critical for upgrades
  end
  else
  begin
    // Set defaults for fresh install
    ServerPort := '5173';
    MaxConcurrentBackups := '2';
  end;
end;

// Called before installation starts - stop existing service
function PrepareToInstall(var NeedsRestart: Boolean): String;
begin
  Result := '';
  
  if IsUpgrade then
  begin
    Log('Upgrade detected - stopping existing service');
    StopService('{#MyAppServiceName}');
  end;
end;

// Skip settings page on upgrade
function ShouldSkipPage(PageID: Integer): Boolean;
begin
  Result := False;
  if (PageID = SettingsPage.ID) and IsUpgrade then
    Result := True;
end;

procedure InitializeWizard;
begin
  // Customize Wizard Colors
  WizardForm.MainPanel.Color := $fff5f5;

  DashboardLinkLabel := TNewStaticText.Create(WizardForm);
  DashboardLinkLabel.Parent := WizardForm.FinishedLabel.Parent;
  DashboardLinkLabel.Left := WizardForm.FinishedLabel.Left;
  DashboardLinkLabel.Top := WizardForm.FinishedLabel.Top;
  DashboardLinkLabel.Cursor := crHand;
  DashboardLinkLabel.Font.Color := clBlue;
  DashboardLinkLabel.Font.Style := DashboardLinkLabel.Font.Style + [fsUnderline];
  DashboardLinkLabel.Visible := False;
  DashboardLinkLabel.OnClick := @DashboardLinkLabelOnClick;

  FinishNoteLabel := TNewStaticText.Create(WizardForm);
  FinishNoteLabel.Parent := WizardForm.FinishedLabel.Parent;
  FinishNoteLabel.Left := WizardForm.FinishedLabel.Left;
  FinishNoteLabel.Top := WizardForm.FinishedLabel.Top;
  FinishNoteLabel.Visible := False;
  
  // --- General Settings Page ---
  // NOTE: Security credentials (Encryption Key, Username, Password) are configured
  // via the web interface after installation and stored in pluton.enc.env and keys.json.
  SettingsPage := CreateInputQueryPage(wpLicense,
    'General Settings', 'Configure the application defaults.',
    'You can change these settings later in the config file.' + #13#10 + #13#10 +
    'NOTE: Security credentials will be configured via the web interface after installation.');

  SettingsPage.Add('Server Port:', False);
  SettingsPage.Add('Max Concurrent Backups:', False);

  // Set hints for Settings Page
  SettingsPage.Edits[0].Hint := 'The port the web interface will listen on.';
  SettingsPage.Edits[0].ShowHint := True;
  SettingsPage.Edits[1].Hint := 'Maximum number of backups to run simultaneously.';
  SettingsPage.Edits[1].ShowHint := True;

  // Set defaults (will be overwritten by NextButtonClick if user changes them)
  SettingsPage.Values[0] := ServerPort;
  SettingsPage.Values[1] := MaxConcurrentBackups;
end;

function NextButtonClick(CurPageID: Integer): Boolean;
begin
  Result := True;

  // Validate Settings Page - only updates values if page was shown
  if CurPageID = SettingsPage.ID then
  begin
    // Store values from user input
    ServerPort := SettingsPage.Values[0];
    MaxConcurrentBackups := SettingsPage.Values[1];
  end;
end;

// Called via BeforeInstall on the 'nssm start' [Run] entry so that
// config.json exists BEFORE the service launches for the first time.
procedure WriteConfigAndUrlFiles;
var
  ConfigPath: String;
  ConfigContent: String;
  DashboardUrl: String;
  UrlFilePath: String;
  UrlFileContent: String;
begin
  DashboardUrl := GetDashboardUrl();

  // Create URL shortcut file with dynamic port
  UrlFilePath := ExpandConstant('{app}\pluton-open.url');
  UrlFileContent := '[InternetShortcut]' + #13#10 +
    'URL=' + DashboardUrl + #13#10 +
    'IconIndex=0' + #13#10 +
    'IconFile=' + ExpandConstant('{app}\pluton.ico');
  SaveStringToFile(UrlFilePath, UrlFileContent, False);

  // Only write config.json if it doesn't exist (preserve user settings on upgrade)
  ConfigPath := ExpandConstant('{commonappdata}\{#MyAppName}\config\config.json');

  if not FileExists(ConfigPath) then
  begin
    // Construct JSON content manually
    ConfigContent := '{' + #13#10 +
      '  "SERVER_PORT": ' + ServerPort + ',' + #13#10 +
      '  "MAX_CONCURRENT_BACKUPS": ' + MaxConcurrentBackups + #13#10 +
      '}';

    if not SaveStringToFile(ConfigPath, ConfigContent, False) then
    begin
      MsgBox('Failed to write configuration file.', mbError, MB_OK);
    end;
  end
  else
  begin
    Log('Config file already exists - preserving user settings');
  end;
end;

// Custom Completion Page
procedure CurPageChanged(CurPageID: Integer);
var
  DashboardUrl: String;
  UpgradeNote: String;
begin
  if CurPageID = wpFinished then
  begin
    DashboardUrl := GetDashboardUrl();

    if IsUpgrade then
      UpgradeNote := 'Pluton has been upgraded successfully.' + #13#10 + #13#10
    else
      UpgradeNote := 'Setup has finished installing Pluton on your computer.' + #13#10 + #13#10;
      
    WizardForm.FinishedLabel.Caption := UpgradeNote +
      'The service has been started successfully.' + #13#10 + #13#10 +
      'Access the dashboard at:';
    WizardForm.AdjustLabelHeight(WizardForm.FinishedLabel);
    DashboardLinkLabel.Caption := DashboardUrl;
    DashboardLinkLabel.Left := WizardForm.FinishedLabel.Left;
    DashboardLinkLabel.Top := WizardForm.FinishedLabel.Top + WizardForm.FinishedLabel.Height + ScaleY(4);
    DashboardLinkLabel.Visible := True;
    FinishNoteLabel.Caption := 'Please click Finish to exit Setup.';
    FinishNoteLabel.Left := WizardForm.FinishedLabel.Left;
    FinishNoteLabel.Top := DashboardLinkLabel.Top + DashboardLinkLabel.Height + ScaleY(8);
    FinishNoteLabel.Visible := True;
      
    // Optional: Open browser
    // ShellExec('open', DashboardUrl, '', '', SW_SHOWNORMAL, ewNoWait, ErrorCode);
  end
  else
  begin
    DashboardLinkLabel.Visible := False;
    FinishNoteLabel.Visible := False;
  end;
end;