# Setup Peaceful Spirit VPN with Pre-Login Access
# Run as Administrator
# This script uses the actual credentials and creates a fully configured VPN connection

# Ensure running as Administrator
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Write-Host "[ERROR] This script must be run as Administrator" -ForegroundColor Red
    Write-Host "Right-click PowerShell and select 'Run as Administrator'" -ForegroundColor Yellow
    exit 1
}

Write-Host "=========================================="
Write-Host "Peaceful Spirit VPN Setup"
Write-Host "=========================================="
Write-Host ""

# Configuration
$VpnName = "Peaceful Spirit VPN"
$ServerAddress = "98.190.129.150"
$L2tpPsk = "z5zkNBds2V9eIkdey09Zm6Khil3DAZs8"
$Username = "pst-admin"
$Password = "24Hearts$"

# Network Configuration (UniFi Router at CC)
$RemoteNetwork = "192.168.0.0/24"  # Peaceful Spirit CC network
$DnsServer = "192.168.0.2"         # DNS server at CC
$Gateway = "192.168.0.10"          # Gateway at CC

Write-Host "[INFO] Configuration:"
Write-Host "  Name: $VpnName"
Write-Host "  Server: $ServerAddress"
Write-Host "  Type: L2TP/IPSec"
Write-Host "  Username: $Username"
Write-Host "  Remote Network: $RemoteNetwork"
Write-Host "  DNS Server: $DnsServer"
Write-Host ""

# Remove existing connection if it exists
Write-Host "[1/6] Checking for existing VPN connection..."
$existing = Get-VpnConnection -Name $VpnName -AllUserConnection -ErrorAction SilentlyContinue
if ($existing) {
    Write-Host "  [INFO] Removing existing connection..."
    Remove-VpnConnection -Name $VpnName -AllUserConnection -Force
    Write-Host "  [OK] Removed"
}
Write-Host "  [OK] Ready to create connection"
Write-Host ""

# Create VPN connection
Write-Host "[2/6] Creating VPN connection..."
try {
    Add-VpnConnection `
        -Name $VpnName `
        -ServerAddress $ServerAddress `
        -TunnelType L2tp `
        -L2tpPsk $L2tpPsk `
        -AuthenticationMethod MsChapv2 `
        -EncryptionLevel Required `
        -AllUserConnection `
        -RememberCredential `
        -SplitTunneling $true `
        -Force
    Write-Host "  [OK] VPN connection created"
    Write-Host "  [OK] Split tunneling enabled (only CC traffic uses VPN)"
} catch {
    Write-Host "  [ERROR] Failed to create connection: $_" -ForegroundColor Red
    exit 1
}
Write-Host ""

# Add route for remote network
Write-Host "[3/6] Configuring route for Peaceful Spirit CC network..."
try {
    # Add route for 192.168.0.0/24 through VPN
    Add-VpnConnectionRoute -ConnectionName $VpnName -DestinationPrefix $RemoteNetwork -AllUserConnection
    Write-Host "  [OK] Route added: $RemoteNetwork via VPN"

    # Configure DNS servers for the VPN connection
    Set-DnsClientServerAddress -InterfaceAlias $VpnName -ServerAddresses $DnsServer -ErrorAction SilentlyContinue
    Write-Host "  [OK] DNS server configured: $DnsServer"
} catch {
    Write-Host "  [WARNING] Could not configure route: $_" -ForegroundColor Yellow
    Write-Host "  [INFO] You may need to add the route manually after connecting"
}
Write-Host ""

# Save credentials
Write-Host "[4/6] Saving VPN credentials for pre-login access..."
try {
    # Connect to save credentials
    $output = rasdial $VpnName $Username $Password 2>&1
    Start-Sleep -Seconds 2

    # Disconnect
    rasdial $VpnName /disconnect 2>&1 | Out-Null
    Start-Sleep -Seconds 1

    Write-Host "  [OK] Credentials saved"
} catch {
    Write-Host "  [WARNING] Could not save credentials: $_" -ForegroundColor Yellow
}
Write-Host ""

# Enable pre-login VPN via registry
Write-Host "[5/6] Enabling pre-login VPN access..."
try {
    $regPath = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"
    Set-ItemProperty -Path $regPath -Name "UseRasCredentials" -Value 1 -Type DWord
    Write-Host "  [OK] Pre-login access enabled"
} catch {
    Write-Host "  [WARNING] Could not set registry value: $_" -ForegroundColor Yellow
}
Write-Host ""

# Verify connection
Write-Host "[6/6] Verifying VPN connection..."
$vpn = Get-VpnConnection -Name $VpnName -AllUserConnection
if ($vpn) {
    Write-Host "  [OK] Connection verified"
    Write-Host ""
    Write-Host "Connection Details:"
    Write-Host "  Name: $($vpn.Name)"
    Write-Host "  Server: $($vpn.ServerAddress)"
    Write-Host "  Type: $($vpn.TunnelType)"
    Write-Host "  All Users: $($vpn.AllUserConnection)"
} else {
    Write-Host "  [ERROR] Connection not found!" -ForegroundColor Red
    exit 1
}
Write-Host ""

# Summary
Write-Host "=========================================="
Write-Host "Setup Complete!"
Write-Host "=========================================="
Write-Host ""
Write-Host "VPN Connection: $VpnName"
Write-Host "  Status: Ready"
Write-Host "  Pre-Login: Enabled"
Write-Host "  Split Tunneling: Enabled"
Write-Host "  Remote Network: $RemoteNetwork"
Write-Host "  DNS Server: $DnsServer"
Write-Host ""
Write-Host "Network Traffic:"
Write-Host "  - Traffic to 192.168.0.0/24 -> VPN tunnel"
Write-Host "  - All other traffic -> Local internet connection"
Write-Host ""
Write-Host "To Connect:"
Write-Host "  PowerShell: rasdial `"$VpnName`""
Write-Host "  Or: GUI -> Network icon -> $VpnName -> Connect"
Write-Host ""
Write-Host "To Disconnect:"
Write-Host "  rasdial `"$VpnName`" /disconnect"
Write-Host ""
Write-Host "At Login Screen:"
Write-Host "  1. Click network icon (bottom right)"
Write-Host "  2. Select '$VpnName'"
Write-Host "  3. Click 'Connect'"
Write-Host "  4. VPN will connect before you log in"
Write-Host ""

# Test connection
Write-Host "Would you like to test the connection now? (Y/N)"
$test = Read-Host
if ($test -eq 'Y' -or $test -eq 'y') {
    Write-Host ""
    Write-Host "Testing VPN connection..."
    Write-Host "=========================================="
    rasdial $VpnName $Username $Password

    Write-Host ""
    Write-Host "Waiting 3 seconds..."
    Start-Sleep -Seconds 3

    Write-Host ""
    Write-Host "Connection Status:"
    Get-VpnConnection -Name $VpnName -AllUserConnection | Select-Object Name, ConnectionStatus, ServerAddress

    Write-Host ""
    Write-Host "Disconnecting..."
    rasdial $VpnName /disconnect

    Write-Host "[OK] Test complete"
    Write-Host ""
}

Write-Host "=========================================="
Write-Host "[SUCCESS] VPN setup complete!"
Write-Host "=========================================="
Write-Host ""
Write-Host "You can now:"
Write-Host "  - Connect from PowerShell: rasdial `"$VpnName`""
Write-Host "  - Connect from login screen before logging in"
Write-Host "  - Connect from Windows network menu"
Write-Host ""
