; BlueSSOFix - GE Aerospace Blue SSO Certificate Fix Utility
; Automates certificate management and WiFi profile configuration for Blue SSO authentication

[Setup]
AppId={{9A8B7C6D-5E4F-3A2B-1C0D-9E8F7A6B5C4D}}
AppName=WJDT BlueSSOFix
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=.\Output
OutputBaseFilename=BlueSSOFix
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 fix Blue SSO wireless authentication issues.%n%nThe installer will:%n- Uninstall and reinstall EAP-PEAP%n- Remove old BLUESSO WiFi profile%n- Install fresh BLUESSO WiFi profile%n- Clean expired certificates%n%nThis is useful when:%n- Blue SSO authentication fails%n- WiFi profile is corrupted%n- Certificate errors appear

[Files]
; Embed the EAP-PEAP installer
Source: "EAP-PEAP.msi"; DestDir: "{tmp}"; Flags: ignoreversion
; Embed the working BLUESSO.xml
Source: "BLUESSO.xml"; DestDir: "{tmp}"; Flags: ignoreversion
; Embed the bat files
Source: "BLUESSO Remove.bat"; DestDir: "{tmp}"; Flags: ignoreversion
Source: "BLUESSO Add Temp.bat"; DestDir: "{tmp}"; Flags: ignoreversion

[Code]
var
  CurrentUsername: String;

procedure InitializeWizard();
begin
  CurrentUsername := GetUserNameString;
end;

procedure CurStepChanged(CurStep: TSetupStep);
var
  ResultCode: Integer;
  ScriptPath: String;
  PowerShellScript: String;
  MsiPath: String;
  XmlPath: String;
begin
  if CurStep = ssInstall then
  begin
    MsiPath := ExpandConstant('{tmp}\EAP-PEAP.msi');

    // Build PowerShell script with nice output
    PowerShellScript :=
      '$ErrorActionPreference = "Continue"' + #13#10 +
      'Write-Host ""' + #13#10 +
      'Write-Host "========================================" -ForegroundColor Cyan' + #13#10 +
      'Write-Host "  BlueSSOFix - Blue SSO Repair Tool" -ForegroundColor Cyan' + #13#10 +
      'Write-Host "========================================" -ForegroundColor Cyan' + #13#10 +
      'Write-Host ""' + #13#10 +
      'Write-Host "Current User: ' + CurrentUsername + '" -ForegroundColor Gray' + #13#10 +
      'Write-Host ""' + #13#10 +
      '' + #13#10 +
      'Write-Host "Step 1: Checking EAP-PEAP installation..." -ForegroundColor Yellow' + #13#10 +
      '$peapInstalled = Test-Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{ED5776D5-59B4-46B7-AF81-5F2D94D7C640}"' + #13#10 +
      'if ($peapInstalled) {' + #13#10 +
      '    Write-Host "  EAP-PEAP already installed" -ForegroundColor Green' + #13#10 +
      '} else {' + #13#10 +
      '    Write-Host "  Installing EAP-PEAP..." -ForegroundColor Yellow' + #13#10 +
      '    $msiPath = "' + MsiPath + '"' + #13#10 +
      '    $process = Start-Process -FilePath "msiexec.exe" -ArgumentList @("/i", "`"$msiPath`"", "/qn", "/norestart") -Wait -PassThru' + #13#10 +
      '    if ($process.ExitCode -eq 0) {' + #13#10 +
      '        Write-Host "  EAP-PEAP installed successfully" -ForegroundColor Green' + #13#10 +
      '        Start-Sleep -Seconds 3' + #13#10 +
      '    } else {' + #13#10 +
      '        Write-Host "  Installation failed with exit code: $($process.ExitCode)" -ForegroundColor Red' + #13#10 +
      '        exit $process.ExitCode' + #13#10 +
      '    }' + #13#10 +
      '}' + #13#10 +
      'Write-Host ""' + #13#10 +
      '' + #13#10 +
      'Write-Host "Step 2: Cleaning expired certificates..." -ForegroundColor Yellow' + #13#10 +
      'try {' + #13#10 +
      '    $expiredCerts = Get-ChildItem -Path Cert:\CurrentUser\My | Where-Object { $_.NotAfter -lt (Get-Date) }' + #13#10 +
      '    if ($expiredCerts) {' + #13#10 +
      '        $removedCount = 0' + #13#10 +
      '        foreach ($cert in $expiredCerts) {' + #13#10 +
      '            try {' + #13#10 +
      '                Remove-Item -Path "Cert:\CurrentUser\My\$($cert.Thumbprint)" -Force -ErrorAction Stop' + #13#10 +
      '                $removedCount++' + #13#10 +
      '            } catch { }' + #13#10 +
      '        }' + #13#10 +
      '        Write-Host "  Removed $removedCount expired certificates" -ForegroundColor Green' + #13#10 +
      '    } else {' + #13#10 +
      '        Write-Host "  No expired certificates found" -ForegroundColor Green' + #13#10 +
      '    }' + #13#10 +
      '} catch {' + #13#10 +
      '    Write-Host "  Error: $_" -ForegroundColor Red' + #13#10 +
      '}' + #13#10 +
      'Write-Host ""' + #13#10 +
      '' + #13#10 +
      'Write-Host "========================================" -ForegroundColor Cyan' + #13#10 +
      'Write-Host "  Phase 1 Complete" -ForegroundColor Cyan' + #13#10 +
      'Write-Host "========================================" -ForegroundColor Cyan' + #13#10 +
      'Write-Host ""' + #13#10 +
      'Write-Host "WiFi profile will be configured next..." -ForegroundColor Yellow' + #13#10 +
      'Write-Host ""';

    ScriptPath := ExpandConstant('{tmp}\BlueSSOFix.ps1');
    SaveStringToFile(ScriptPath, PowerShellScript, False);

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

    DeleteFile(ScriptPath);
  end;

  if CurStep = ssPostInstall then
  begin
    // Build nice PowerShell script for WiFi configuration
    XmlPath := ExpandConstant('{commonappdata}\BLUESSO.xml');
    CopyFile(ExpandConstant('{tmp}\BLUESSO.xml'), XmlPath, False);

    PowerShellScript :=
      'Write-Host ""' + #13#10 +
      'Write-Host "Step 3: Configuring WiFi profile..." -ForegroundColor Yellow' + #13#10 +
      'Write-Host "  Removing old BLUESSO profile..." -ForegroundColor Gray' + #13#10 +
      'Write-Host ""';

    ScriptPath := ExpandConstant('{tmp}\BlueSSOFix_WiFi.ps1');
    SaveStringToFile(ScriptPath, PowerShellScript, False);

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

    DeleteFile(ScriptPath);

    // Create scheduled task to run as current user (non-elevated)
    Exec('cmd.exe',
         '/c schtasks /create /tn "BlueSSOFix_WiFi" /tr "cmd.exe /c netsh wlan delete profile name=BLUESSO & netsh wlan add profile filename=' + XmlPath + '" /sc once /st 00:00 /ru "' + CurrentUsername + '" /f',
         '', SW_HIDE, ewWaitUntilTerminated, ResultCode);

    // Run the scheduled task immediately
    Exec('cmd.exe',
         '/c schtasks /run /tn "BlueSSOFix_WiFi"',
         '', SW_HIDE, ewWaitUntilTerminated, ResultCode);

    Sleep(2000);

    // Delete the scheduled task
    Exec('cmd.exe',
         '/c schtasks /delete /tn "BlueSSOFix_WiFi" /f',
         '', SW_HIDE, ewWaitUntilTerminated, ResultCode);

    // Final success message
    PowerShellScript :=
      'Write-Host "  WiFi profile configured successfully" -ForegroundColor Green' + #13#10 +
      'Write-Host ""' + #13#10 +
      'Write-Host "========================================" -ForegroundColor Cyan' + #13#10 +
      'Write-Host "  BlueSSOFix Complete!" -ForegroundColor Cyan' + #13#10 +
      'Write-Host "========================================" -ForegroundColor Cyan' + #13#10 +
      'Write-Host ""' + #13#10 +
      'Write-Host "Summary:" -ForegroundColor White' + #13#10 +
      'Write-Host "  [OK] EAP-PEAP installed" -ForegroundColor Green' + #13#10 +
      'Write-Host "  [OK] BLUESSO WiFi profile configured" -ForegroundColor Green' + #13#10 +
      'Write-Host "  [OK] Expired certificates cleaned" -ForegroundColor Green' + #13#10 +
      'Write-Host ""' + #13#10 +
      'Write-Host "Press any key to continue..." -ForegroundColor Gray' + #13#10 +
      '$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")';

    ScriptPath := ExpandConstant('{tmp}\BlueSSOFix_Complete.ps1');
    SaveStringToFile(ScriptPath, PowerShellScript, False);

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

    DeleteFile(ScriptPath);
  end;
end;
