# PST L2TP/IPsec VPN Setup Script
# Run as Administrator

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "PST L2TP/IPsec VPN Setup" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan

# Check if running as Administrator
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

if (-not $isAdmin) {
    Write-Host "`n[ERROR] This script must be run as Administrator!" -ForegroundColor Red
    Write-Host "Right-click PowerShell and select 'Run as Administrator'" -ForegroundColor Yellow
    pause
    exit 1
}

# VPN Configuration
$vpnName = "PST-NW-VPN"
$serverAddress = "64.139.88.249"
$psk = "rrClvnmUeXEFo90Ol+z7tfsAZHeSK6w7"
$username = "pst-admin"
$password = "24Hearts$"

Write-Host "`nStep 1: Creating VPN Connection..." -ForegroundColor Yellow

# Remove existing VPN connection if it exists
$existing = Get-VpnConnection -Name $vpnName -AllUserConnection -ErrorAction SilentlyContinue
if ($existing) {
    Write-Host "Removing existing VPN connection..." -ForegroundColor Gray
    Remove-VpnConnection -Name $vpnName -AllUserConnection -Force
}

# Create new L2TP/IPsec VPN connection (All Users - for pre-login)
try {
    Add-VpnConnection `
        -Name $vpnName `
        -ServerAddress $serverAddress `
        -TunnelType L2tp `
        -EncryptionLevel Required `
        -AuthenticationMethod MSChapv2 `
        -L2tpPsk $psk `
        -AllUserConnection `
        -RememberCredential `
        -PassThru `
        -Force

    Write-Host "[OK] VPN connection created" -ForegroundColor Green
}
catch {
    Write-Host "[ERROR] Failed to create VPN connection: $_" -ForegroundColor Red
    pause
    exit 1
}

Write-Host "`nStep 2: Configuring Split-Tunnel and DNS..." -ForegroundColor Yellow

# Configure split-tunnel (don't route all traffic through VPN)
try {
    Set-VpnConnection -Name $vpnName -SplitTunneling $true -AllUserConnection
    Write-Host "[OK] Split-tunneling enabled (only remote network traffic uses VPN)" -ForegroundColor Green
}
catch {
    Write-Host "[WARNING] Could not enable split-tunneling: $_" -ForegroundColor Yellow
}

# Set DNS server for VPN connection
try {
    # Get the VPN interface (will be available after first connection)
    # We'll set this after the test connection
    Write-Host "[INFO] DNS will be configured after first connection" -ForegroundColor Gray
}
catch {
    Write-Host "[WARNING] Could not configure DNS: $_" -ForegroundColor Yellow
}

Write-Host "`nStep 3: Configuring IPsec Settings..." -ForegroundColor Yellow

# Set VPN connection to use pre-shared key
try {
    Set-VpnConnectionIPsecConfiguration `
        -ConnectionName $vpnName `
        -AuthenticationTransformConstants SHA256128 `
        -CipherTransformConstants AES128 `
        -EncryptionMethod AES128 `
        -IntegrityCheckMethod SHA256 `
        -DHGroup Group14 `
        -PfsGroup None `
        -Force

    Write-Host "[OK] IPsec settings configured" -ForegroundColor Green
}
catch {
    Write-Host "[WARNING] Could not set advanced IPsec settings: $_" -ForegroundColor Yellow
    Write-Host "Using default IPsec configuration" -ForegroundColor Gray
}

Write-Host "`nStep 4: Saving VPN Credentials..." -ForegroundColor Yellow

# Create secure credential
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force

# Save credentials using rasdial (works for pre-login)
try {
    # Use rasdial to save credentials in the system
    $rasDialCmd = "rasdial `"$vpnName`" $username $password"

    # Connect once to save credentials, then disconnect
    Write-Host "Testing connection and saving credentials..." -ForegroundColor Gray
    $result = cmd /c "rasdial `"$vpnName`" $username $password" 2>&1

    if ($LASTEXITCODE -eq 0) {
        Write-Host "[OK] Connection successful - credentials saved" -ForegroundColor Green

        # Configure DNS for VPN interface
        Start-Sleep -Seconds 3
        Write-Host "Configuring DNS server (192.168.0.2)..." -ForegroundColor Gray

        try {
            # Get the VPN interface
            $vpnInterface = Get-NetAdapter | Where-Object { $_.InterfaceDescription -like "*WAN Miniport (L2TP)*" -and $_.Status -eq "Up" }

            if ($vpnInterface) {
                Set-DnsClientServerAddress -InterfaceIndex $vpnInterface.InterfaceIndex -ServerAddresses "192.168.0.2"
                Write-Host "[OK] DNS set to 192.168.0.2" -ForegroundColor Green
            }
            else {
                Write-Host "[WARNING] Could not find active VPN interface for DNS config" -ForegroundColor Yellow
            }
        }
        catch {
            Write-Host "[WARNING] Could not set DNS: $_" -ForegroundColor Yellow
        }

        # Disconnect
        Start-Sleep -Seconds 2
        rasdial $vpnName /disconnect | Out-Null
        Write-Host "[OK] Disconnected" -ForegroundColor Green
    }
    else {
        Write-Host "[WARNING] Connection test failed, but credentials may be saved" -ForegroundColor Yellow
        Write-Host "Error: $result" -ForegroundColor Gray
    }
}
catch {
    Write-Host "[WARNING] Could not test connection: $_" -ForegroundColor Yellow
}

Write-Host "`nStep 5: Configuring Auto-Connect (Optional)..." -ForegroundColor Yellow
Write-Host "Creating Task Scheduler job for auto-connect at startup..." -ForegroundColor Gray

# Create a scheduled task to connect at startup (before login)
$taskName = "PST-VPN-AutoConnect"

# Remove existing task if present
Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue

# Copy the connection script to a system location
$scriptSource = "D:\ClaudeTools\Connect-PST-VPN.ps1"
$scriptDest = "C:\Windows\System32\Connect-PST-VPN.ps1"

if (Test-Path $scriptSource) {
    Copy-Item $scriptSource -Destination $scriptDest -Force
    Write-Host "[OK] Connection script copied to system directory" -ForegroundColor Green
}

# Create task action to run PowerShell script
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-ExecutionPolicy Bypass -WindowStyle Hidden -File `"$scriptDest`""

# Create task trigger (at startup)
$trigger = New-ScheduledTaskTrigger -AtStartup

# Create task principal (run as SYSTEM for pre-login)
$principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount -RunLevel Highest

# Create task settings
$settings = New-ScheduledTaskSettingsSet `
    -AllowStartIfOnBatteries `
    -DontStopIfGoingOnBatteries `
    -StartWhenAvailable `
    -RestartCount 3 `
    -RestartInterval (New-TimeSpan -Minutes 1)

# Register the task
try {
    Register-ScheduledTask `
        -TaskName $taskName `
        -Action $action `
        -Trigger $trigger `
        -Principal $principal `
        -Settings $settings `
        -Description "Auto-connect to PST VPN at system startup" | Out-Null

    Write-Host "[OK] Auto-connect scheduled task created" -ForegroundColor Green
}
catch {
    Write-Host "[WARNING] Could not create scheduled task: $_" -ForegroundColor Yellow
}

# Summary
Write-Host "`n========================================" -ForegroundColor Cyan
Write-Host "Setup Complete!" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Cyan

Write-Host "`nVPN Configuration:" -ForegroundColor White
Write-Host "  Name: $vpnName" -ForegroundColor Gray
Write-Host "  Server: $serverAddress" -ForegroundColor Gray
Write-Host "  Type: L2TP/IPsec with Pre-Shared Key" -ForegroundColor Gray
Write-Host "  Username: $username" -ForegroundColor Gray
Write-Host "  Tunnel Mode: Split-Tunnel (only remote traffic uses VPN)" -ForegroundColor Gray
Write-Host "  DNS Server: 192.168.0.2" -ForegroundColor Gray
Write-Host "  Auto-connect: Enabled (scheduled task)" -ForegroundColor Gray

Write-Host "`nConnection Methods:" -ForegroundColor White
Write-Host "  1. Windows Settings > Network > VPN > '$vpnName' > Connect" -ForegroundColor Gray
Write-Host "  2. Command line: powershell -File C:\Windows\System32\Connect-PST-VPN.ps1" -ForegroundColor Gray
Write-Host "  3. Simple: rasdial `"$vpnName`" (DNS must be set manually)" -ForegroundColor Gray
Write-Host "  4. Automatic at startup (via scheduled task with DNS config)" -ForegroundColor Gray

Write-Host "`nPre-Login Connection:" -ForegroundColor White
Write-Host "  - This VPN is available to all users" -ForegroundColor Gray
Write-Host "  - Will auto-connect at system startup" -ForegroundColor Gray
Write-Host "  - Credentials are saved system-wide" -ForegroundColor Gray

Write-Host "`nManagement:" -ForegroundColor White
Write-Host "  - View connection: Get-VpnConnection -Name '$vpnName' -AllUserConnection" -ForegroundColor Gray
Write-Host "  - Connect manually: rasdial '$vpnName'" -ForegroundColor Gray
Write-Host "  - Disconnect: rasdial '$vpnName' /disconnect" -ForegroundColor Gray
Write-Host "  - Remove VPN: Remove-VpnConnection -Name '$vpnName' -AllUserConnection" -ForegroundColor Gray
Write-Host "  - Remove auto-connect: Unregister-ScheduledTask -TaskName '$taskName'" -ForegroundColor Gray

Write-Host "`n"
pause
