; Simplified Script for GE Aerospace Mapped Drive Reconnection Utility
; Clean approach: Record → Disconnect → Update Credentials → Reconnect

[Setup]
AppId={{C7D8E9F0-A1B2-3C4D-5E6F-7A8B9C0D1E2F}
AppName=WJDT GE Aerospace Mapped Drive Reconnection
AppVersion=2.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=MappedDriveReconnect_v2
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 update your network drive credentials and reconnect all mapped drives.%n%nSimple process:%n1. Record current drives%n2. Disconnect all drives%n3. Update credentials%n4. Reconnect drives%n%nYou will be prompted for your logon domain password.

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

var
  PasswordPage: TInputQueryWizardPage;
  CurrentUsername: String;
  UserPassword: String;

procedure InitializeWizard();
begin
  CurrentUsername := GetUserNameString;

  PasswordPage := CreateInputQueryPage(wpWelcome,
    'Enter Network Credentials',
    'Please enter your password for the logon domain',
    'Your username: logon\' + CurrentUsername + #13#10#13#10 +
    'Enter your password below:');

  PasswordPage.Add('Password:', True);
end;

function NextButtonClick(CurPageID: Integer): Boolean;
var
  ResultCode: Integer;
  ScriptPath: String;
  PowerShellScript: String;
begin
  Result := True;

  if CurPageID = PasswordPage.ID then
  begin
    UserPassword := PasswordPage.Values[0];

    if Trim(UserPassword) = '' then
    begin
      MsgBox('Password cannot be empty. Please enter your password.', mbError, MB_OK);
      Result := False;
      Exit;
    end;

    if MsgBox('Username: logon\' + CurrentUsername + #13#10#13#10 +
              'Ready to update credentials and reconnect drives?',
              mbConfirmation, MB_YESNO) = IDNO then
    begin
      Result := False;
      Exit;
    end;
  end;

  if CurPageID = wpReady then
  begin
    PowerShellScript :=
      '# Simplified Drive Reconnection Script' + #13#10 +
      '$username = "logon\' + CurrentUsername + '"' + #13#10 +
      '$password = [System.Environment]::GetEnvironmentVariable("TEMP_GE_PASSWORD","Process")' + #13#10 +
      '[System.Environment]::SetEnvironmentVariable("TEMP_GE_PASSWORD",$null,"Process")' + #13#10 +
      '' + #13#10 +
      'Write-Host "========================================" -ForegroundColor Cyan' + #13#10 +
      'Write-Host "  GE Drive Reconnection Tool v2.0" -ForegroundColor Cyan' + #13#10 +
      'Write-Host "========================================" -ForegroundColor Cyan' + #13#10 +
      'Write-Host ""' + #13#10 +
      '' + #13#10 +
      '# ============================================' + #13#10 +
      '# STEP 1: Record Current Mapped Drives' + #13#10 +
      '# ============================================' + #13#10 +
      'Write-Host "Step 1: Recording current mapped drives..." -ForegroundColor Yellow' + #13#10 +
      '$savedDrives = @()' + #13#10 +
      '$netUseOutput = net use 2>&1' + #13#10 +
      '' + #13#10 +
      'foreach ($line in $netUseOutput) {' + #13#10 +
      '    # Match pattern: "Status    Local    Remote                    Network"' + #13#10 +
      '    #                "OK        S:       \\server\share            Microsoft..."' + #13#10 +
      '    if ($line -match "^\w+\s+([A-Z]:)\s+(\\\\[^\s]+)") {' + #13#10 +
      '        $drive = $matches[1]' + #13#10 +
      '        $path = $matches[2]' + #13#10 +
      '        $savedDrives += @{Drive=$drive; Path=$path}' + #13#10 +
      '        Write-Host "  Found: $drive -> $path" -ForegroundColor Gray' + #13#10 +
      '    }' + #13#10 +
      '}' + #13#10 +
      '' + #13#10 +
      'if ($savedDrives.Count -eq 0) {' + #13#10 +
      '    Write-Host "  No mapped drives found" -ForegroundColor Gray' + #13#10 +
      '}' + #13#10 +
      'Write-Host ""' + #13#10 +
      '' + #13#10 +
      '# ============================================' + #13#10 +
      '# STEP 2: Disconnect All Mapped Drives' + #13#10 +
      '# ============================================' + #13#10 +
      'Write-Host "Step 2: Disconnecting all mapped drives..." -ForegroundColor Yellow' + #13#10 +
      'foreach ($drive in $savedDrives) {' + #13#10 +
      '    Write-Host "  Disconnecting $($drive.Drive)..." -ForegroundColor Gray' + #13#10 +
      '    net use $($drive.Drive) /delete /yes 2>&1 | Out-Null' + #13#10 +
      '}' + #13#10 +
      'Write-Host "  All drives disconnected" -ForegroundColor Green' + #13#10 +
      'Write-Host ""' + #13#10 +
      '' + #13#10 +
      '# ============================================' + #13#10 +
      '# STEP 3: Extract Unique Hostnames' + #13#10 +
      '# ============================================' + #13#10 +
      'Write-Host "Step 3: Identifying unique servers..." -ForegroundColor Yellow' + #13#10 +
      '$uniqueServers = @()' + #13#10 +
      '' + #13#10 +
      'foreach ($drive in $savedDrives) {' + #13#10 +
      '    # Extract hostname from \\hostname\share' + #13#10 +
      '    if ($drive.Path -match "^\\\\([^\\]+)") {' + #13#10 +
      '        $hostname = $matches[1]' + #13#10 +
      '        if ($uniqueServers -notcontains $hostname) {' + #13#10 +
      '            $uniqueServers += $hostname' + #13#10 +
      '            Write-Host "  Found server: $hostname" -ForegroundColor Gray' + #13#10 +
      '        }' + #13#10 +
      '    }' + #13#10 +
      '}' + #13#10 +
      'Write-Host ""' + #13#10 +
      '' + #13#10 +
      '# ============================================' + #13#10 +
      '# STEP 4: Delete Old Credentials' + #13#10 +
      '# ============================================' + #13#10 +
      'Write-Host "Step 4: Removing old credentials from Windows Credential Manager..." -ForegroundColor Yellow' + #13#10 +
      'foreach ($server in $uniqueServers) {' + #13#10 +
      '    Write-Host "  Deleting credentials for: $server" -ForegroundColor Gray' + #13#10 +
      '    cmdkey /delete:$server 2>&1 | Out-Null' + #13#10 +
      '}' + #13#10 +
      'Write-Host "  Old credentials removed" -ForegroundColor Green' + #13#10 +
      'Write-Host ""' + #13#10 +
      '' + #13#10 +
      '# ============================================' + #13#10 +
      '# STEP 5: Add New Credentials' + #13#10 +
      '# ============================================' + #13#10 +
      'Write-Host "Step 5: Adding new credentials to Windows Credential Manager..." -ForegroundColor Yellow' + #13#10 +
      'foreach ($server in $uniqueServers) {' + #13#10 +
      '    Write-Host "  Adding credentials for: $server" -ForegroundColor Gray' + #13#10 +
      '    $result = cmdkey /add:$server /user:$username /pass:$password 2>&1' + #13#10 +
      '    if ($LASTEXITCODE -eq 0) {' + #13#10 +
      '        Write-Host "    Success!" -ForegroundColor Green' + #13#10 +
      '    } else {' + #13#10 +
      '        Write-Host "    Warning: $result" -ForegroundColor Yellow' + #13#10 +
      '    }' + #13#10 +
      '}' + #13#10 +
      'Write-Host ""' + #13#10 +
      '' + #13#10 +
      '# ============================================' + #13#10 +
      '# STEP 6: Reconnect Drives (Auto-Auth)' + #13#10 +
      '# ============================================' + #13#10 +
      'Write-Host "Step 6: Reconnecting drives (using stored credentials)..." -ForegroundColor Yellow' + #13#10 +
      '$successCount = 0' + #13#10 +
      '$failCount = 0' + #13#10 +
      '' + #13#10 +
      'foreach ($drive in $savedDrives) {' + #13#10 +
      '    Write-Host "  Mapping $($drive.Drive) -> $($drive.Path)..." -ForegroundColor Cyan' + #13#10 +
      '    ' + #13#10 +
      '    # Let Windows pull credentials automatically from Credential Manager' + #13#10 +
      '    $mapResult = net use $($drive.Drive) $($drive.Path) /persistent:yes 2>&1' + #13#10 +
      '    ' + #13#10 +
      '    if ($LASTEXITCODE -eq 0) {' + #13#10 +
      '        Write-Host "    Success!" -ForegroundColor Green' + #13#10 +
      '        $successCount++' + #13#10 +
      '    } else {' + #13#10 +
      '        Write-Host "    Failed: $mapResult" -ForegroundColor Red' + #13#10 +
      '        $failCount++' + #13#10 +
      '    }' + #13#10 +
      '}' + #13#10 +
      '' + #13#10 +
      '# Clear password from memory' + #13#10 +
      '$password = $null' + #13#10 +
      '' + #13#10 +
      'Write-Host ""' + #13#10 +
      'Write-Host "========================================" -ForegroundColor Cyan' + #13#10 +
      '' + #13#10 +
      '# ============================================' + #13#10 +
      '# STEP 7: Display Results' + #13#10 +
      '# ============================================' + #13#10 +
      'if ($failCount -eq 0) {' + #13#10 +
      '    $Host.UI.RawUI.BackgroundColor = "DarkGreen"' + #13#10 +
      '    Clear-Host' + #13#10 +
      '    Write-Host ""' + #13#10 +
      '    Write-Host "  ========================================" -ForegroundColor Green' + #13#10 +
      '    Write-Host "  SUCCESS!" -ForegroundColor Green' + #13#10 +
      '    Write-Host "  ========================================" -ForegroundColor Green' + #13#10 +
      '    Write-Host ""' + #13#10 +
      '    Write-Host "  All $successCount drive(s) reconnected successfully!" -ForegroundColor White' + #13#10 +
      '    Write-Host ""' + #13#10 +
      '    Write-Host "  Current mapped drives:" -ForegroundColor Yellow' + #13#10 +
      '    net use | Select-String ":" | ForEach-Object {' + #13#10 +
      '        if ($_ -match "([A-Z]:)\s+(\\\\[^\s]+)") {' + #13#10 +
      '            Write-Host "    $($matches[1]) -> $($matches[2])" -ForegroundColor Gray' + #13#10 +
      '        }' + #13#10 +
      '    }' + #13#10 +
      '    Write-Host ""' + #13#10 +
      '} else {' + #13#10 +
      '    $Host.UI.RawUI.BackgroundColor = "DarkYellow"' + #13#10 +
      '    Clear-Host' + #13#10 +
      '    Write-Host ""' + #13#10 +
      '    Write-Host "  ========================================" -ForegroundColor Yellow' + #13#10 +
      '    Write-Host "  PARTIAL SUCCESS" -ForegroundColor Yellow' + #13#10 +
      '    Write-Host "  ========================================" -ForegroundColor Yellow' + #13#10 +
      '    Write-Host ""' + #13#10 +
      '    Write-Host "  Successfully reconnected: $successCount drive(s)" -ForegroundColor Green' + #13#10 +
      '    Write-Host "  Failed to reconnect: $failCount drive(s)" -ForegroundColor Red' + #13#10 +
      '    Write-Host ""' + #13#10 +
      '    Write-Host "  Possible reasons for failure:" -ForegroundColor White' + #13#10 +
      '    Write-Host "    - Incorrect password" -ForegroundColor Gray' + #13#10 +
      '    Write-Host "    - Server unreachable" -ForegroundColor Gray' + #13#10 +
      '    Write-Host "    - Share no longer exists" -ForegroundColor Gray' + #13#10 +
      '    Write-Host ""' + #13#10 +
      '}' + #13#10 +
      '' + #13#10 +
      'Write-Host "  Press any key to close..." -ForegroundColor Gray' + #13#10 +
      '$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")' + #13#10 +
      '$Host.UI.RawUI.BackgroundColor = "Black"' + #13#10;

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

    SetEnvironmentVariable('TEMP_GE_PASSWORD', UserPassword);

    if not Exec('powershell.exe',
                '-NoProfile -ExecutionPolicy Bypass -File "' + ScriptPath + '"',
                '', SW_SHOW, ewWaitUntilTerminated, ResultCode) then
    begin
      MsgBox('Failed to execute script.', mbError, MB_OK);
      Result := False;
    end;

    SetEnvironmentVariable('TEMP_GE_PASSWORD', '');
    DeleteFile(ScriptPath);
  end;
end;

function ShouldSkipPage(PageID: Integer): Boolean;
begin
  Result := False;
end;

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