# ============================================================================
# 00 — Enable OpenSSH Server trên Windows Server
# USAGE:
#   1. RDP vào VPS (103.124.94.58:3389)
#   2. Mở PowerShell AS ADMINISTRATOR
#   3. Copy-paste TOÀN BỘ file này vào PowerShell rồi Enter
#   4. Chờ ~1 phút, script sẽ print "DONE" khi xong
#   5. Báo lại cho dev để test SSH
#
# Script idempotent — chạy nhiều lần OK.
# ============================================================================

#Requires -RunAsAdministrator

$ErrorActionPreference = 'Stop'
$ProgressPreference    = 'SilentlyContinue'

Write-Host ""
Write-Host "=========================================================" -ForegroundColor Cyan
Write-Host " DYD — Enable OpenSSH Server on Windows" -ForegroundColor Cyan
Write-Host "=========================================================" -ForegroundColor Cyan

# --- 1. Install OpenSSH Server capability ---
Write-Host ""
Write-Host "[1/6] Install OpenSSH.Server capability ..." -ForegroundColor Yellow
$cap = Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH.Server*'
if ($cap.State -ne 'Installed') {
    Add-WindowsCapability -Online -Name $cap.Name | Out-Null
    Write-Host "  [OK] Installed" -ForegroundColor Green
}
else {
    Write-Host "  [OK] Already installed" -ForegroundColor Green
}

# --- 2. Start sshd + auto-start ---
Write-Host ""
Write-Host "[2/6] Start sshd service ..." -ForegroundColor Yellow
Start-Service sshd
Set-Service -Name sshd -StartupType Automatic
# Start ssh-agent too (tùy, cho key management)
Set-Service -Name ssh-agent -StartupType Automatic
Start-Service ssh-agent -ErrorAction SilentlyContinue
Write-Host "  [OK] sshd running, auto-start enabled" -ForegroundColor Green

# --- 3. Firewall rule port 22 ---
Write-Host ""
Write-Host "[3/6] Firewall rule port 22 ..." -ForegroundColor Yellow
$rule = Get-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -ErrorAction SilentlyContinue
if (-not $rule) {
    New-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' `
        -DisplayName 'OpenSSH SSH Server (sshd)' `
        -Enabled True -Direction Inbound -Protocol TCP -Action Allow `
        -LocalPort 22 | Out-Null
    Write-Host "  [OK] Firewall rule created" -ForegroundColor Green
}
else {
    Enable-NetFirewallRule -Name 'OpenSSH-Server-In-TCP'
    Write-Host "  [OK] Firewall rule enabled" -ForegroundColor Green
}

# --- 4. Set DefaultShell = PowerShell (thay cho cmd) ---
Write-Host ""
Write-Host "[4/6] Set DefaultShell = PowerShell ..." -ForegroundColor Yellow
New-ItemProperty -Path 'HKLM:\SOFTWARE\OpenSSH' `
    -Name DefaultShell `
    -Value 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe' `
    -PropertyType String -Force | Out-Null
Write-Host "  [OK] DefaultShell set to PowerShell" -ForegroundColor Green

# --- 5. Add dev machine public key to authorized_keys ---
Write-Host ""
Write-Host "[5/6] Add dev public key ..." -ForegroundColor Yellow

# === PUBLIC KEY ĐÃ EMBED — KHÔNG commit private key ===
$PublicKey = 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIM/SmlEVa41JmeIAwQOtEkdzUo1BLPJbJ+oDqDYm1ywQ dyd-vps-deploy-20260415'

# For Administrator account, dùng C:\ProgramData\ssh\administrators_authorized_keys
# (KHÔNG dùng ~/.ssh/authorized_keys)
$authFile = 'C:\ProgramData\ssh\administrators_authorized_keys'

# Ensure directory exists
$authDir = Split-Path $authFile
if (-not (Test-Path $authDir)) {
    New-Item -ItemType Directory -Path $authDir -Force | Out-Null
}

# Append key nếu chưa có (idempotent)
$existing = if (Test-Path $authFile) { Get-Content $authFile -Raw } else { '' }
if ($existing -notmatch [regex]::Escape($PublicKey)) {
    Add-Content -Path $authFile -Value $PublicKey -Encoding UTF8
    Write-Host "  [OK] Public key added" -ForegroundColor Green
}
else {
    Write-Host "  [OK] Public key already present" -ForegroundColor Green
}

# Fix permission — QUAN TRỌNG, sai permission = SSH silently reject key
# Chỉ Administrators + SYSTEM được đọc
icacls $authFile /inheritance:r | Out-Null
icacls $authFile /grant 'Administrators:F' /grant 'SYSTEM:F' | Out-Null
Write-Host "  [OK] Permission locked (Admin + SYSTEM only)" -ForegroundColor Green

# --- 6. Verify ---
Write-Host ""
Write-Host "[6/6] Verify ..." -ForegroundColor Yellow

$sshd = Get-Service sshd
if ($sshd.Status -eq 'Running') {
    Write-Host "  [OK] sshd: Running" -ForegroundColor Green
}
else {
    Write-Host "  [FAIL] sshd: $($sshd.Status)" -ForegroundColor Red
}

# Test listener
$listening = Get-NetTCPConnection -LocalPort 22 -State Listen -ErrorAction SilentlyContinue
if ($listening) {
    Write-Host "  [OK] Port 22: listening on $($listening[0].LocalAddress)" -ForegroundColor Green
}
else {
    Write-Host "  [WARN] Port 22: not listening (may need restart)" -ForegroundColor Yellow
}

# Test firewall
$fw = Get-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -ErrorAction SilentlyContinue
if ($fw -and $fw.Enabled -eq 'True') {
    Write-Host "  [OK] Firewall: allowed" -ForegroundColor Green
}

# --- DONE ---
Write-Host ""
Write-Host "=========================================================" -ForegroundColor Green
Write-Host " DONE — SSH server ready" -ForegroundColor Green
Write-Host "=========================================================" -ForegroundColor Green
Write-Host ""
Write-Host "Dev machine can now connect:"
Write-Host "  ssh -i ~/.ssh/dyd_vps Administrator@103.124.94.58" -ForegroundColor Yellow
Write-Host ""
Write-Host "Test từ máy dev:"
Write-Host "  ssh -i ~/.ssh/dyd_vps Administrator@103.124.94.58 hostname" -ForegroundColor Yellow
Write-Host ""
Write-Host "[!] Nếu đổi ý muốn disable SSH sau, chạy:"
Write-Host "    Stop-Service sshd; Set-Service sshd -StartupType Disabled"
