# Troubleshoot and fix PST VPN authentication
# Run as Administrator

Write-Host "PST VPN Authentication Troubleshooter" -ForegroundColor Cyan
Write-Host "======================================`n" -ForegroundColor Cyan

$vpnName = "PST-NW-VPN"

# Check if running as admin
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
    Write-Host "[ERROR] Must run as Administrator!" -ForegroundColor Red
    pause
    exit 1
}

# Get current VPN settings
Write-Host "Current VPN Configuration:" -ForegroundColor Yellow
$vpn = Get-VpnConnection -Name $vpnName -AllUserConnection -ErrorAction SilentlyContinue

if (-not $vpn) {
    Write-Host "[ERROR] VPN connection '$vpnName' not found!" -ForegroundColor Red
    Write-Host "Run Setup-PST-L2TP-VPN.ps1 first" -ForegroundColor Yellow
    pause
    exit 1
}

Write-Host "  Server: $($vpn.ServerAddress)" -ForegroundColor Gray
Write-Host "  Tunnel Type: $($vpn.TunnelType)" -ForegroundColor Gray
Write-Host "  Auth Method: $($vpn.AuthenticationMethod -join ', ')" -ForegroundColor Gray
Write-Host "  Encryption: $($vpn.EncryptionLevel)" -ForegroundColor Gray
Write-Host "  Split Tunnel: $($vpn.SplitTunneling)" -ForegroundColor Gray

# Check authentication settings
Write-Host "`nChecking authentication settings..." -ForegroundColor Yellow

# For UniFi, we need to ensure proper authentication
Write-Host "Configuring authentication for UniFi L2TP..." -ForegroundColor Cyan

try {
    # Remove and recreate with correct settings
    Write-Host "Reconfiguring VPN with UniFi-compatible settings..." -ForegroundColor Gray

    Remove-VpnConnection -Name $vpnName -AllUserConnection -Force -ErrorAction SilentlyContinue

    # Create with PAP or CHAP (UniFi may require these instead of MSChapv2)
    Add-VpnConnection `
        -Name $vpnName `
        -ServerAddress "64.139.88.249" `
        -TunnelType L2tp `
        -EncryptionLevel Optional `
        -AuthenticationMethod Chap,MSChapv2 `
        -L2tpPsk "rrClvnmUeXEFo90Ol+z7tfsAZHeSK6w7" `
        -AllUserConnection `
        -RememberCredential `
        -SplitTunneling $true `
        -Force

    Write-Host "[OK] VPN recreated with CHAP + MSChapv2 authentication" -ForegroundColor Green

    # Configure IPsec
    Set-VpnConnectionIPsecConfiguration `
        -ConnectionName $vpnName `
        -AuthenticationTransformConstants SHA256128 `
        -CipherTransformConstants AES128 `
        -EncryptionMethod AES128 `
        -IntegrityCheckMethod SHA256 `
        -DHGroup Group14 `
        -PfsGroup None `
        -Force `
        -ErrorAction SilentlyContinue

    Write-Host "[OK] IPsec configuration updated" -ForegroundColor Green
}
catch {
    Write-Host "[WARNING] Configuration update had issues: $_" -ForegroundColor Yellow
}

# Test connection
Write-Host "`nTesting connection..." -ForegroundColor Yellow
Write-Host "Username: pst-admin" -ForegroundColor Gray
Write-Host "Attempting to connect..." -ForegroundColor Gray

$result = cmd /c 'rasdial "PST-NW-VPN" pst-admin "24Hearts$"' 2>&1

if ($LASTEXITCODE -eq 0) {
    Write-Host "`n[SUCCESS] Connection successful!" -ForegroundColor Green

    Start-Sleep -Seconds 2

    # Show connection status
    rasdial

    # Disconnect
    Write-Host "`nDisconnecting..." -ForegroundColor Gray
    rasdial "PST-NW-VPN" /disconnect | Out-Null
}
else {
    Write-Host "`n[FAILED] Connection still failing" -ForegroundColor Red
    Write-Host "Error: $result" -ForegroundColor Gray

    Write-Host "`n=== TROUBLESHOOTING STEPS ===" -ForegroundColor Yellow
    Write-Host ""
    Write-Host "1. Verify credentials on UniFi server:" -ForegroundColor White
    Write-Host "   - Login to UniFi controller" -ForegroundColor Gray
    Write-Host "   - Settings > VPN > L2TP Remote Access VPN" -ForegroundColor Gray
    Write-Host "   - Check that user 'pst-admin' exists with correct password" -ForegroundColor Gray
    Write-Host ""
    Write-Host "2. Check UniFi VPN server settings:" -ForegroundColor White
    Write-Host "   - Ensure L2TP VPN is enabled" -ForegroundColor Gray
    Write-Host "   - Verify pre-shared key matches: rrClvnmUeXEFo90Ol+z7tfsAZHeSK6w7" -ForegroundColor Gray
    Write-Host "   - Check authentication methods allowed (CHAP/MSChapv2)" -ForegroundColor Gray
    Write-Host ""
    Write-Host "3. Verify network connectivity:" -ForegroundColor White
    Write-Host "   - Can you reach the server? Run: ping 64.139.88.249" -ForegroundColor Gray
    Write-Host "   - Check if ports are open: UDP 500, 1701, 4500" -ForegroundColor Gray
    Write-Host ""
    Write-Host "4. Try alternative authentication:" -ForegroundColor White
    Write-Host "   - The server may require PAP authentication" -ForegroundColor Gray
    Write-Host "   - Try enabling PAP in Windows (see below)" -ForegroundColor Gray
    Write-Host ""
    Write-Host "5. Registry fix for PAP (if needed):" -ForegroundColor White
    Write-Host "   Run: rasphone -d `"PST-NW-VPN`"" -ForegroundColor Gray
    Write-Host "   Security tab > Advanced > Check 'Allow these protocols:'" -ForegroundColor Gray
    Write-Host "   Enable: 'Unencrypted password (PAP)' and 'Challenge Handshake (CHAP)'" -ForegroundColor Gray
    Write-Host ""
    Write-Host "6. Common UniFi L2TP issues:" -ForegroundColor White
    Write-Host "   - Username might need @domain suffix (e.g., pst-admin@peacefulspirit)" -ForegroundColor Gray
    Write-Host "   - Check if user account is enabled on UniFi" -ForegroundColor Gray
    Write-Host "   - Verify RADIUS server is not required" -ForegroundColor Gray
}

Write-Host ""
pause
