#define MyAppName "ИС Грузоперевозки"
#define MyAppVersion "1.0"
#define MyAppPublisher "Политехнический колледж НовГУ"
#define MyAppExeName "WpfApp1.exe"

[Setup]
AppId={{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}
AppName={#MyAppName}
AppVersion={#MyAppVersion}
AppPublisher={#MyAppPublisher}
DefaultDirName={autopf}\{#MyAppName}
DefaultGroupName={#MyAppName}
AllowNoIcons=yes
OutputDir=C:\FreightInstaller\Output
OutputBaseFilename=Setup_FreightTransport_v1.0
Compression=lzma2/ultra64
SolidCompression=yes
WizardStyle=modern
ArchitecturesInstallIn64BitMode=x64
PrivilegesRequired=admin

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

[Files]
Source: "C:\Users\Татьяна\Desktop\FreightInstaller\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs

Source: "C:\Users\Татьяна\Desktop\FreightInstaller\create_tables.sql"; DestDir: "{tmp}"; Flags: dontcopy
Source: "C:\Users\Татьяна\Desktop\FreightInstaller\create_views.sql"; DestDir: "{tmp}"; Flags: dontcopy
Source: "C:\Users\Татьяна\Desktop\FreightInstaller\insert_test_data.sql"; DestDir: "{tmp}"; Flags: dontcopy

[Icons]
Name: "{group}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"
Name: "{group}\{cm:UninstallProgram,{#MyAppName}}"; Filename: "{uninstallexe}"
Name: "{commondesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"

[Run]
Filename: "{app}\{#MyAppExeName}"; Description: "Запустить ИС Грузоперевозки"; Flags: nowait postinstall skipifsilent

[Code]
function SetEnvironmentVariable(lpName: String; lpValue: String): Boolean;
  external 'SetEnvironmentVariableA@kernel32.dll stdcall';

var
  DbPasswordPage: TInputQueryWizardPage;

procedure InitializeWizard();
begin
  DbPasswordPage := CreateInputQueryPage(wpSelectDir,
    'Настройка базы данных',
    'Укажите параметры подключения к PostgreSQL',
    'Для автоматической инициализации БД введите пароль суперпользователя postgres:');
  DbPasswordPage.Add('Пароль пользователя postgres:', True);
  DbPasswordPage.Values[0] := '';
end;

procedure CurStepChanged(CurStep: TSetupStep);
var
  ResultCode: Integer;
  PsqlPath: String;
  DbName, DbUser, DbPassword: String;
  Params, SqlDir: String;
begin
  if CurStep <> ssPostInstall then Exit;
  
  DbPassword := DbPasswordPage.Values[0];
  if DbPassword = '' then
  begin
    MsgBox('Пароль не введён. Инициализация БД пропущена.' + #13#10 +
           'Выполните SQL-скрипты вручную из папки: ' + #13#10 +
           ExpandConstant('{app}\'),
           mbInformation, MB_OK);
    Exit;
  end;

  DbName := 'freight_db';
  DbUser := 'postgres';

  PsqlPath := 'C:\Program Files\PostgreSQL\18\bin\psql.exe';
  if not FileExists(PsqlPath) then
    PsqlPath := 'C:\Program Files\PostgreSQL\17\bin\psql.exe';
  if not FileExists(PsqlPath) then
    PsqlPath := 'C:\Program Files\PostgreSQL\16\bin\psql.exe';
  if not FileExists(PsqlPath) then
    PsqlPath := 'C:\Program Files\PostgreSQL\15\bin\psql.exe';
  if not FileExists(PsqlPath) then
    PsqlPath := 'C:\Program Files\PostgreSQL\14\bin\psql.exe';
  
  if PsqlPath = '' then
  begin
    MsgBox('psql.exe не найден.', mbError, MB_OK);
    Exit;
  end;
  
  ExtractTemporaryFile('create_tables.sql');
  ExtractTemporaryFile('create_views.sql');
  ExtractTemporaryFile('insert_test_data.sql');
  SqlDir := ExpandConstant('{tmp}');

  SetEnvironmentVariable('PGPASSWORD', DbPassword);
  
  Params := '-U ' + DbUser + ' -d postgres -c "CREATE DATABASE ' + DbName + ';"';
  Exec(PsqlPath, Params, '', SW_HIDE, ewWaitUntilTerminated, ResultCode);
  
  Params := '-U ' + DbUser + ' -d ' + DbName + ' -f "' + SqlDir + '\create_tables.sql"';
  Exec(PsqlPath, Params, '', SW_HIDE, ewWaitUntilTerminated, ResultCode);
  
  Params := '-U ' + DbUser + ' -d ' + DbName + ' -f "' + SqlDir + '\create_views.sql"';
  Exec(PsqlPath, Params, '', SW_HIDE, ewWaitUntilTerminated, ResultCode);
  
  Params := '-U ' + DbUser + ' -d ' + DbName + ' -f "' + SqlDir + '\insert_test_data.sql"';
  Exec(PsqlPath, Params, '', SW_HIDE, ewWaitUntilTerminated, ResultCode);
  
  SetEnvironmentVariable('PGPASSWORD', '');
  
  MsgBox('База данных "' + DbName + '" успешно создана и заполнена!' + #13#10 +
         'SQL-скрипты сохранены в: ' + ExpandConstant('{app}\'),
         mbInformation, MB_OK);
end;