#Requires -RunAsAdministrator
Set-ExecutionPolicy Bypass -Scope Process -Force
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"

# Fixed install paths (must match appsettings.json hardcoded paths)
$installRoot  = "C:\velapanel.com"
$installDir   = $installRoot + "\publish"
$dataDir      = $installRoot + "\data"
$svcName      = "VelaPanel"
$svcUser      = "PanelSvc"
$svcPassword  = "VelaSvc@Panel1!"
$panelPort    = 5100
$panelPortTls = 5101

# Source = one folder up from this script (the extracted zip root)
$sourceDir = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path

# ------------------------------------------------------------------
# MENU
# ------------------------------------------------------------------
Write-Host ""
Write-Host "==================================================" -ForegroundColor Cyan
Write-Host "  VelaPanel Server Setup" -ForegroundColor Cyan
Write-Host "==================================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "  [1] Install VelaPanel"
Write-Host "  [2] Uninstall VelaPanel"
Write-Host "  [3] Exit"
Write-Host ""
$choice = Read-Host "Select an option"

switch ($choice) {

    # ==============================================================
    "1" {
    # ==============================================================

        Write-Host ""
        Write-Host "==================================================" -ForegroundColor Cyan
        Write-Host "  Installing VelaPanel..." -ForegroundColor Cyan
        Write-Host "==================================================" -ForegroundColor Cyan
        Write-Host "  Source  : $sourceDir"
        Write-Host "  Install : $installDir"
        Write-Host "  Data    : $dataDir"
        Write-Host ""

        # Phase 1: Preflight
        Write-Host "[1/9] Preflight checks..." -ForegroundColor Yellow

        $os = [System.Environment]::OSVersion.Version
        if ($os.Major -lt 10 -or ($os.Major -eq 10 -and $os.Build -lt 17763)) {
            throw "Windows Server 2019 (build 17763) or later required. Current: $os"
        }
        Write-Host "      OS: OK (Build $($os.Build))" -ForegroundColor Green

        $freeGB = [math]::Round((Get-PSDrive C).Free / 1GB, 1)
        if ($freeGB -lt 2) { throw "Less than 2 GB free on C: ($freeGB GB)." }
        Write-Host "      Disk: OK ($freeGB GB free)" -ForegroundColor Green

        if (-not (Test-Path (Join-Path $sourceDir "VelaPanel.exe"))) {
            throw "VelaPanel.exe not found in: $sourceDir"
        }
        Write-Host "      Source files: OK" -ForegroundColor Green

        $existingService = Get-Service $svcName -ErrorAction SilentlyContinue
        if ($existingService) {
            Write-Warning "VelaPanel service already exists (Status: $($existingService.Status))."
            $answer = Read-Host "Continue and overwrite? [y/N]"
            if ($answer -notmatch '^y') { Write-Host "Aborted."; exit 0 }
            if ($existingService.Status -eq "Running") {
                Stop-Service $svcName -Force
                Start-Sleep -Seconds 3
            }
            sc.exe delete $svcName | Out-Null
            Start-Sleep -Seconds 2
        }
        Write-Host "      Preflight: PASSED" -ForegroundColor Green

        # Phase 2: IIS Features
        Write-Host "[2/9] Installing IIS features (may take a few minutes)..." -ForegroundColor Yellow

        $iisFeatures = @(
            "Web-Server", "Web-Mgmt-Tools", "Web-Mgmt-Console",
            "Web-Asp-Net45", "Web-CGI", "Web-ISAPI-Ext", "Web-ISAPI-Filter",
            "Web-Default-Doc", "Web-Http-Errors", "Web-Static-Content",
            "Web-Http-Logging", "Web-Log-Libraries", "Web-Stat-Compression",
            "Web-Dyn-Compression", "Web-Url-Auth", "Web-Windows-Auth",
            "Web-Http-Redirect", "Web-WebSockets"
        )

        $result = Install-WindowsFeature -Name $iisFeatures -IncludeManagementTools
        if (-not $result.Success) { throw "IIS feature installation failed." }
        Write-Host "      IIS features installed." -ForegroundColor Green

        # Phase 3: Directories
        Write-Host "[3/9] Creating directory structure..." -ForegroundColor Yellow

        foreach ($d in @(
            $installDir, $dataDir,
            ($dataDir + "\backups"),
            ($dataDir + "\logs"),
            ($dataDir + "\logs\archive"),
            ($dataDir + "\keys"),
            ($dataDir + "\quarantine"),
            ($dataDir + "\zones")
        )) {
            if (-not (Test-Path $d)) { New-Item -ItemType Directory -Path $d -Force | Out-Null }
        }
        Write-Host "      Directories created." -ForegroundColor Green

        # Phase 4: Copy files
        Write-Host "[4/9] Copying panel files to $installDir ..." -ForegroundColor Yellow

        $srcResolved = (Resolve-Path $sourceDir).Path
        $dstResolved = (Resolve-Path $installDir).Path

        if ($srcResolved -ne $dstResolved) {
            Copy-Item ($sourceDir + "\*") $installDir -Recurse -Force
            Write-Host "      Files copied." -ForegroundColor Green
        } else {
            Write-Host "      Source is already the install dir, skipping copy." -ForegroundColor Gray
        }

        $exe = $installDir + "\VelaPanel.exe"
        if (-not (Test-Path $exe)) { throw "VelaPanel.exe missing after copy." }
        Write-Host "      VelaPanel.exe verified." -ForegroundColor Green

        # Lift the update / rollback scripts and tools\ folder shipped in the build up to the
        # install root, so they run from the documented C:\velapanel.com\ location and survive
        # the publish swap performed by deploy-update. Thereafter deploy-update/rollback keep
        # these root copies in sync automatically — no manual copying ever needed.
        foreach ($s in @("deploy-update.ps1", "rollback-update.ps1")) {
            $src = Join-Path $installDir $s
            if (Test-Path $src) { Copy-Item $src (Join-Path $installRoot $s) -Force }
        }
        $srcTools = Join-Path $installDir "tools"
        if (Test-Path $srcTools) {
            $dstTools = Join-Path $installRoot "tools"
            if (-not (Test-Path $dstTools)) { New-Item -ItemType Directory -Path $dstTools -Force | Out-Null }
            Copy-Item (Join-Path $srcTools "*") $dstTools -Recurse -Force
        }
        Write-Host "      Update/rollback scripts + tools\ placed at $installRoot." -ForegroundColor Green

        # Phase 5: Permissions (LocalSystem — no user account needed)
        Write-Host "[5/9] Setting permissions..." -ForegroundColor Yellow

        icacls $dataDir    /grant "SYSTEM:(OI)(CI)F"  | Out-Null
        icacls $installDir /grant "SYSTEM:(OI)(CI)RX" | Out-Null
        Write-Host "      ACLs applied (LocalSystem)." -ForegroundColor Green

        # Phase 6: Register service
        Write-Host "[6/9] Registering Windows Service..." -ForegroundColor Yellow

        sc.exe create $svcName binPath= ("`"" + $exe + "`"") start= auto obj= "LocalSystem" | Out-Null
        sc.exe description $svcName "Windows Hosting Control Panel" | Out-Null
        sc.exe failure $svcName reset= 86400 actions= restart/60000/restart/60000/restart/60000 | Out-Null
        Write-Host "      Service '$svcName' registered (auto-start)." -ForegroundColor Green

        # Phase 7: Firewall
        Write-Host "[7/9] Creating firewall rules..." -ForegroundColor Yellow

        if (-not (Get-NetFirewallRule -DisplayName "VelaPanel HTTP" -ErrorAction SilentlyContinue)) {
            New-NetFirewallRule -DisplayName "VelaPanel HTTP" -Direction Inbound `
                -Protocol TCP -LocalPort $panelPort -Action Allow | Out-Null
        }
        if (-not (Get-NetFirewallRule -DisplayName "VelaPanel HTTPS" -ErrorAction SilentlyContinue)) {
            New-NetFirewallRule -DisplayName "VelaPanel HTTPS" -Direction Inbound `
                -Protocol TCP -LocalPort $panelPortTls -Action Allow | Out-Null
        }
        Write-Host "      Firewall rules created (ports $panelPort, $panelPortTls)." -ForegroundColor Green

        # Phase 8: Config reminder
        Write-Host "[8/9] Configuration reminder..." -ForegroundColor Yellow
        Write-Host "      Edit before first use: $installDir\appsettings.json" -ForegroundColor White
        Write-Host "        - Seeding:AdminPassword  (change from default)" -ForegroundColor Gray
        Write-Host "        - Acme:AccountEmail      (for SSL certificates)" -ForegroundColor Gray
        Write-Host "        - Database:MySql/MsSql   (if using external DB servers)" -ForegroundColor Gray

        # Phase 9: Start and verify
        Write-Host "[9/9] Starting VelaPanel..." -ForegroundColor Yellow

        try {
            Start-Service $svcName -ErrorAction Stop
        } catch {
            $evt = Get-EventLog -LogName Application -Newest 10 -ErrorAction SilentlyContinue |
                   Where-Object { $_.Source -match "VelaPanel|\.NET Runtime|Application Error" } |
                   Select-Object -First 3
            Write-Warning "Service failed to start. Recent errors:"
            foreach ($e in $evt) {
                Write-Warning ("  [" + $e.Source + "] " + $e.Message.Split("`n")[0])
            }
            Write-Warning ("Full logs: " + $dataDir + "\logs\")
            exit 1
        }

        Start-Sleep -Seconds 5

        $ready = $false
        for ($i = 0; $i -lt 6; $i++) {
            try {
                $resp = Invoke-WebRequest ("http://localhost:" + $panelPort) `
                            -UseBasicParsing -TimeoutSec 5 -ErrorAction SilentlyContinue
                if ($null -ne $resp -and $resp.StatusCode -lt 500) { $ready = $true; break }
            } catch { }
            $elapsed = ($i + 1) * 5
            Write-Host "      Waiting... ($elapsed s)" -ForegroundColor Gray
            Start-Sleep -Seconds 5
        }

        Write-Host ""
        if ($ready) {
            $hostname = $env:COMPUTERNAME
            Write-Host "==================================================" -ForegroundColor Green
            Write-Host "  SUCCESS - VelaPanel is running!" -ForegroundColor Green
            Write-Host "==================================================" -ForegroundColor Green
            Write-Host ""
            Write-Host ("  URL      : http://" + $hostname + ":" + $panelPort)
            Write-Host "  Login    : admin@localhost"
            Write-Host "  Password : CHANGE-THIS-NOW-Admin1!"
            Write-Host ""
            Write-Host "  *** CHANGE THE ADMIN PASSWORD IMMEDIATELY ***" -ForegroundColor Red
            Write-Host ""
            Write-Host ("  Config : " + $installDir + "\appsettings.json")
            Write-Host ("  Logs   : " + $dataDir + "\logs")
            Write-Host ""
        } else {
            Write-Host "==================================================" -ForegroundColor Yellow
            Write-Host "  Service started but panel not yet responding." -ForegroundColor Yellow
            Write-Host "==================================================" -ForegroundColor Yellow
            Write-Host ""
            Write-Host "  First-run DB migration may still be running."
            Write-Host ("  Wait 30s then open: http://localhost:" + $panelPort)
            Write-Host ("  Logs: " + $dataDir + "\logs")
            Write-Host ""
        }
    }

    # ==============================================================
    "2" {
    # ==============================================================

        Write-Host ""
        Write-Host "==================================================" -ForegroundColor Red
        Write-Host "  Uninstalling VelaPanel..." -ForegroundColor Red
        Write-Host "==================================================" -ForegroundColor Red
        Write-Host ""
        Write-Host "  This will:" -ForegroundColor White
        Write-Host "    - Stop and delete the VelaPanel Windows Service"
        Write-Host "    - Delete the PanelSvc user account"
        Write-Host "    - Remove firewall rules"
        Write-Host ""
        $keepData = Read-Host "Keep data and config files in $($installRoot)? [Y/n]"
        $confirm  = Read-Host "Are you sure you want to uninstall? [y/N]"
        if ($confirm -notmatch '^y') { Write-Host "Aborted."; exit 0 }

        # Step 1: Stop and delete service
        Write-Host ""
        Write-Host "[1/4] Stopping and removing service..." -ForegroundColor Yellow

        $svc = Get-Service $svcName -ErrorAction SilentlyContinue
        if ($svc) {
            if ($svc.Status -eq "Running") {
                Stop-Service $svcName -Force -ErrorAction SilentlyContinue
                Start-Sleep -Seconds 3
            }
            # Kill any remaining process
            Get-Process -Name VelaPanel -ErrorAction SilentlyContinue | Stop-Process -Force
            Start-Sleep -Seconds 2

            sc.exe delete $svcName | Out-Null
            Write-Host "      Service deleted." -ForegroundColor Green
            Write-Host "      Note: if error 1072 appears, close services.msc and reboot to complete deletion." -ForegroundColor Gray
        } else {
            Write-Host "      Service not found, skipping." -ForegroundColor Gray
        }

        # Step 2: Service runs as LocalSystem — no user account to remove
        Write-Host "[2/4] Skipping service account removal (LocalSystem)." -ForegroundColor Gray

        # Step 3: Remove firewall rules
        Write-Host "[3/4] Removing firewall rules..." -ForegroundColor Yellow

        Remove-NetFirewallRule -DisplayName "VelaPanel HTTP"  -ErrorAction SilentlyContinue
        Remove-NetFirewallRule -DisplayName "VelaPanel HTTPS" -ErrorAction SilentlyContinue
        Write-Host "      Firewall rules removed." -ForegroundColor Green

        # Step 4: Remove files (optional)
        Write-Host "[4/4] Removing files..." -ForegroundColor Yellow

        if ($keepData -match '^n') {
            if (Test-Path $installRoot) {
                Remove-Item $installRoot -Recurse -Force
                Write-Host "      Removed $installRoot" -ForegroundColor Green
            } else {
                Write-Host "      $installRoot not found, skipping." -ForegroundColor Gray
            }
        } else {
            Write-Host "      Data kept at $installRoot" -ForegroundColor Gray
        }

        Write-Host ""
        Write-Host "==================================================" -ForegroundColor Green
        Write-Host "  VelaPanel uninstalled." -ForegroundColor Green
        Write-Host "==================================================" -ForegroundColor Green
        Write-Host ""
        if ($keepData -notmatch '^n') {
            Write-Host "  Data and config retained at: $installRoot"
            Write-Host "  Delete manually if no longer needed:"
            Write-Host ("  Remove-Item " + $installRoot + " -Recurse -Force")
        }
        Write-Host ""
    }

    # ==============================================================
    "3" {
    # ==============================================================
        Write-Host "Exiting." -ForegroundColor Gray
        exit 0
    }

    default {
        Write-Host "Invalid option. Run the script again and choose 1, 2, or 3." -ForegroundColor Red
        exit 1
    }
}
