; HID Card Printer Driver Installer
; Installs drivers for HID card printers (DTC4500e, DTC1250e, etc.)

[Setup]
AppId={{9F7E2B3C-4A1D-5E8F-B6C9-1D3A5F7E2C4B}}
AppName=WJDT HID Card Printer Driver Installer
AppVersion=1.0
AppPublisher=WJDT
AppPublisherURL=http://tsgwp00524.logon.ds.ge.com
AppSupportURL=http://tsgwp00524.logon.ds.ge.com
AppUpdatesURL=http://tsgwp00524.logon.ds.ge.com
CreateAppDir=no
ChangesAssociations=no
PrivilegesRequired=admin
OutputDir=C:\Users\570005354\Downloads\Output
OutputBaseFilename=HIDCardPrinterInstaller
SolidCompression=yes
WizardStyle=modern
SetupIconFile=gea-logo.ico
WizardImageFile=patrick.bmp
WizardSmallImageFile=patrick-sm.bmp
CreateUninstallRegKey=no
DisableWelcomePage=no

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

[Messages]
WelcomeLabel2=This utility will install HID card printer drivers for badge and ID card printing.%n%nIt will:%n- Install HID card printer drivers%n- Support USB-connected card printers%n- Configure drivers for Windows%n%nSupported Models:%n- HID FARGO DTC4500e%n- HID FARGO DTC1250e%n- HID FARGO HDP5000%n%nClick Next to continue.

[Files]
; HID DTC4500e Driver
Source: "drivers\HID_DTC4500e\*"; DestDir: "{tmp}\hid_dtc4500e"; Flags: ignoreversion recursesubdirs

; Add additional HID models here as needed
; Source: "drivers\HID_DTC1250e\*"; DestDir: "{tmp}\hid_dtc1250e"; Flags: ignoreversion recursesubdirs
; Source: "drivers\HID_HDP5000\*"; DestDir: "{tmp}\hid_hdp5000"; Flags: ignoreversion recursesubdirs

[Code]
var
  ModelSelectionPage: TInputOptionWizardPage;
  AvailableModels: array of record
    ModelName: String;
    DriverPath: String;
    InfFile: String;
    DriverDisplayName: String;
  end;

// Initialize available printer models
procedure InitializeModels();
begin
  SetArrayLength(AvailableModels, 1);  // Expand to 3 when you have more drivers

  // HID FARGO DTC4500e
  AvailableModels[0].ModelName := 'HID FARGO DTC4500e';
  AvailableModels[0].DriverPath := ExpandConstant('{tmp}\hid_dtc4500e');
  AvailableModels[0].InfFile := 'dtc4500e.inf';  // Update with actual INF filename
  AvailableModels[0].DriverDisplayName := 'HID FARGO DTC4500e Card Printer';

  // Add more models when drivers are available:
  // AvailableModels[1].ModelName := 'HID FARGO DTC1250e';
  // AvailableModels[1].DriverPath := ExpandConstant('{tmp}\hid_dtc1250e');
  // AvailableModels[1].InfFile := 'dtc1250e.inf';
  // AvailableModels[1].DriverDisplayName := 'HID FARGO DTC1250e Card Printer';
end;

// Check which drivers are already installed
function CheckInstalledDrivers(): Boolean;
var
  ResultCode: Integer;
  TempScriptPath, TempOutputPath: String;
  PSScript: String;
  Output: AnsiString;
  Lines: TStringList;
  I, J: Integer;
  FoundDriver: Boolean;
begin
  Result := False;

  // Build PowerShell script to get installed printer drivers
  PSScript :=
    'try {' + #13#10 +
    '    Get-PrinterDriver | Select-Object -ExpandProperty Name | ForEach-Object { Write-Output $_ }' + #13#10 +
    '} catch { exit 1 }';

  TempScriptPath := ExpandConstant('{tmp}\check_drivers.ps1');
  TempOutputPath := ExpandConstant('{tmp}\drivers_output.txt');

  SaveStringToFile(TempScriptPath, PSScript, False);

  if not Exec('powershell.exe',
       '-NoProfile -ExecutionPolicy Bypass -Command "& ''' + TempScriptPath + ''' | Out-File -FilePath ''' + TempOutputPath + ''' -Encoding ASCII"',
       '', SW_HIDE, ewWaitUntilTerminated, ResultCode) then
  begin
    DeleteFile(TempScriptPath);
    Exit;
  end;

  DeleteFile(TempScriptPath);

  if not FileExists(TempOutputPath) then
    Exit;

  if not LoadStringFromFile(TempOutputPath, Output) then
  begin
    DeleteFile(TempOutputPath);
    Exit;
  end;

  DeleteFile(TempOutputPath);

  Lines := TStringList.Create;
  try
    Lines.Text := Output;
    Result := True;  // Successfully retrieved driver list
  finally
    Lines.Free;
  end;
end;

// Initialize wizard pages
procedure InitializeWizard();
var
  I: Integer;
  DisplayText: String;
begin
  // Initialize available models
  InitializeModels();

  // Check which drivers are installed
  CheckInstalledDrivers();

  // Create model selection page
  ModelSelectionPage := CreateInputOptionPage(wpWelcome,
    'Select Card Printer Models',
    'Choose which HID card printer drivers to install',
    'Select the models you need. Drivers will be installed for USB-connected card printers.',
    False,
    False);

  // Add models to selection page
  for I := 0 to GetArrayLength(AvailableModels) - 1 do
  begin
    DisplayText := AvailableModels[I].ModelName + ' - USB Card Printer';
    ModelSelectionPage.Add(DisplayText);

    // Default to selected
    ModelSelectionPage.Values[I] := True;
  end;
end;

// Validate selection before continuing
function NextButtonClick(CurPageID: Integer): Boolean;
var
  I: Integer;
  HasSelection: Boolean;
begin
  Result := True;

  if CurPageID = ModelSelectionPage.ID then
  begin
    HasSelection := False;

    // Check if at least one model is selected
    for I := 0 to GetArrayLength(AvailableModels) - 1 do
    begin
      if ModelSelectionPage.Values[I] then
      begin
        HasSelection := True;
        Break;
      end;
    end;

    if not HasSelection then
    begin
      MsgBox('Please select at least one printer model to install.',
             mbInformation, MB_OK);
      Result := False;
    end;
  end;
end;

// Install drivers during installation phase
procedure CurStepChanged(CurStep: TSetupStep);
var
  I: Integer;
  PSScript: String;
  TempScriptPath: String;
  ResultCode: Integer;
  SelectedCount: Integer;
begin
  // Run after files are extracted but before finishing
  if CurStep = ssPostInstall then
  begin
    // Count selected models
    SelectedCount := 0;
    for I := 0 to GetArrayLength(AvailableModels) - 1 do
    begin
      if ModelSelectionPage.Values[I] then
        SelectedCount := SelectedCount + 1;
    end;

    if SelectedCount = 0 then
      Exit;

    // Build PowerShell installation script
    PSScript :=
      '$ErrorActionPreference = "Continue"' + #13#10 +
      'Write-Host ""' + #13#10 +
      'Write-Host "========================================"  -ForegroundColor Cyan' + #13#10 +
      'Write-Host "  HID Card Printer Driver Installer" -ForegroundColor Cyan' + #13#10 +
      'Write-Host "========================================"  -ForegroundColor Cyan' + #13#10 +
      'Write-Host ""' + #13#10 +
      '' + #13#10 +
      '# Function to install card printer driver' + #13#10 +
      'function Install-CardPrinterDriver {' + #13#10 +
      '    param(' + #13#10 +
      '        [string]$ModelName,' + #13#10 +
      '        [string]$DriverPath,' + #13#10 +
      '        [string]$InfFile' + #13#10 +
      '    )' + #13#10 +
      '' + #13#10 +
      '    try {' + #13#10 +
      '        Write-Host ""' + #13#10 +
      '        Write-Host "Installing: $ModelName" -ForegroundColor Cyan' + #13#10 +
      '        Write-Host "  Driver Path: $DriverPath" -ForegroundColor Gray' + #13#10 +
      '' + #13#10 +
      '        $infPath = Join-Path $DriverPath $InfFile' + #13#10 +
      '        if (-not (Test-Path $infPath)) {' + #13#10 +
      '            Write-Host "  ERROR: INF file not found: $infPath" -ForegroundColor Red' + #13#10 +
      '            return $false' + #13#10 +
      '        }' + #13#10 +
      '' + #13#10 +
      '        Write-Host "  INF File: $InfFile" -ForegroundColor Gray' + #13#10 +
      '' + #13#10 +
      '        # Locate pnputil.exe' + #13#10 +
      '        $pnputil = $null' + #13#10 +
      '        $pnputilLocations = @(' + #13#10 +
      '            (Join-Path $env:SystemRoot "System32\pnputil.exe"),' + #13#10 +
      '            (Join-Path $env:SystemRoot "SysNative\pnputil.exe"),' + #13#10 +
      '            "C:\Windows\System32\pnputil.exe"' + #13#10 +
      '        )' + #13#10 +
      '' + #13#10 +
      '        foreach ($location in $pnputilLocations) {' + #13#10 +
      '            if (Test-Path $location) {' + #13#10 +
      '                $pnputil = $location' + #13#10 +
      '                break' + #13#10 +
      '            }' + #13#10 +
      '        }' + #13#10 +
      '' + #13#10 +
      '        if (-not $pnputil) {' + #13#10 +
      '            $pnputil = "pnputil.exe"' + #13#10 +
      '        }' + #13#10 +
      '' + #13#10 +
      '        # Install driver package using pnputil' + #13#10 +
      '        Write-Host "  Installing driver package..." -ForegroundColor Yellow' + #13#10 +
      '        try {' + #13#10 +
      '            $pnpResult = & $pnputil /add-driver $infPath /install /force 2>&1' + #13#10 +
      '            $pnpExitCode = $LASTEXITCODE' + #13#10 +
      '' + #13#10 +
      '            # Exit code 0 = success, 259 = driver already installed' + #13#10 +
      '            if ($pnpExitCode -eq 0 -or $pnpExitCode -eq 259) {' + #13#10 +
      '                if ($pnpExitCode -eq 259) {' + #13#10 +
      '                    Write-Host "  Driver already installed" -ForegroundColor Green' + #13#10 +
      '                } else {' + #13#10 +
      '                    Write-Host "  Driver package installed successfully" -ForegroundColor Green' + #13#10 +
      '                }' + #13#10 +
      '                return $true' + #13#10 +
      '            } else {' + #13#10 +
      '                Write-Host "  Warning: pnputil returned code $pnpExitCode" -ForegroundColor Yellow' + #13#10 +
      '                Write-Host "  $pnpResult" -ForegroundColor Gray' + #13#10 +
      '                return $false' + #13#10 +
      '            }' + #13#10 +
      '        } catch {' + #13#10 +
      '            Write-Host "  ERROR: $_" -ForegroundColor Red' + #13#10 +
      '            return $false' + #13#10 +
      '        }' + #13#10 +
      '    } catch {' + #13#10 +
      '        Write-Host "  ERROR: $_" -ForegroundColor Red' + #13#10 +
      '        return $false' + #13#10 +
      '    }' + #13#10 +
      '}' + #13#10 +
      '' + #13#10 +
      'Write-Host "Installing selected HID card printer drivers..." -ForegroundColor Cyan' + #13#10 +
      'Write-Host ""' + #13#10 +
      '' + #13#10 +
      '$successCount = 0' + #13#10 +
      '$failCount = 0' + #13#10 +
      '' + #13#10;

    // Add installation commands for each selected model
    for I := 0 to GetArrayLength(AvailableModels) - 1 do
    begin
      if ModelSelectionPage.Values[I] then
      begin
        PSScript := PSScript +
          'if (Install-CardPrinterDriver -ModelName "' + AvailableModels[I].ModelName + '" ' +
          '-DriverPath "' + AvailableModels[I].DriverPath + '" ' +
          '-InfFile "' + AvailableModels[I].InfFile + '") {' + #13#10 +
          '    $successCount++' + #13#10 +
          '} else {' + #13#10 +
          '    $failCount++' + #13#10 +
          '}' + #13#10;
      end;
    end;

    // Add summary
    PSScript := PSScript +
      '' + #13#10 +
      'Write-Host ""' + #13#10 +
      'Write-Host "========================================"  -ForegroundColor Cyan' + #13#10 +
      'Write-Host "  Installation Complete" -ForegroundColor Cyan' + #13#10 +
      'Write-Host "========================================"  -ForegroundColor Cyan' + #13#10 +
      'Write-Host ""' + #13#10 +
      'if ($successCount -gt 0) {' + #13#10 +
      '    Write-Host "  Drivers installed: $successCount" -ForegroundColor Green' + #13#10 +
      '}' + #13#10 +
      'if ($failCount -gt 0) {' + #13#10 +
      '    Write-Host "  Failed installations: $failCount" -ForegroundColor Red' + #13#10 +
      '}' + #13#10 +
      'Write-Host ""' + #13#10 +
      'Write-Host "Next Steps:" -ForegroundColor Cyan' + #13#10 +
      'Write-Host "  1. Connect your HID card printer via USB" -ForegroundColor Gray' + #13#10 +
      'Write-Host "  2. Windows will detect and configure it automatically" -ForegroundColor Gray' + #13#10 +
      'Write-Host "  3. Go to Devices and Printers to verify" -ForegroundColor Gray' + #13#10 +
      'Write-Host ""' + #13#10 +
      'Write-Host "Press any key to close..." -ForegroundColor Gray' + #13#10 +
      '$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")';

    // Save and execute script
    TempScriptPath := ExpandConstant('{tmp}\install_hid_drivers.ps1');
    SaveStringToFile(TempScriptPath, PSScript, False);

    Exec('powershell.exe',
         '-NoProfile -ExecutionPolicy Bypass -File "' + TempScriptPath + '"',
         '', SW_SHOW, ewWaitUntilTerminated, ResultCode);

    DeleteFile(TempScriptPath);
  end;
end;

// Skip directory selection
function ShouldSkipPage(PageID: Integer): Boolean;
begin
  Result := False;
  if PageID = wpSelectDir then
    Result := True;
end;
