# ============================================================================
# 04 — Install Gitea 1.23 + NSSM service (port 3000, SQLite)
# Run as Administrator. Pattern từ NamGroup skill cicd-gitea-windows.
# ============================================================================

#Requires -RunAsAdministrator

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

$GiteaDir = 'C:\Gitea'
$DataDir  = 'C:\Gitea\data'
$LogsDir  = 'C:\Gitea\log'
$NSSMDir  = 'C:\Tools\nssm'

# --- DOWNLOAD GITEA ---------------------------------------------------------
Write-Host "1/5 — Download Gitea 1.23.7" -ForegroundColor Cyan
New-Item -ItemType Directory -Force -Path $GiteaDir, $DataDir, $LogsDir | Out-Null

$giteaExe = "$GiteaDir\gitea.exe"
if (-not (Test-Path $giteaExe)) {
    $url = 'https://dl.gitea.com/gitea/1.23.7/gitea-1.23.7-windows-4.0-amd64.exe'
    Invoke-WebRequest -Uri $url -OutFile $giteaExe
    Write-Host "  [OK] gitea.exe downloaded" -ForegroundColor Green
} else {
    Write-Host "  [OK] gitea.exe exists" -ForegroundColor Green
}

# --- DOWNLOAD NSSM ----------------------------------------------------------
Write-Host "2/5 — Download NSSM" -ForegroundColor Cyan
New-Item -ItemType Directory -Force -Path $NSSMDir | Out-Null

$nssmExe = "$NSSMDir\nssm.exe"
if (-not (Test-Path $nssmExe)) {
    $zip = "$env:TEMP\nssm.zip"
    Invoke-WebRequest -Uri 'https://nssm.cc/release/nssm-2.24.zip' -OutFile $zip
    Expand-Archive -Path $zip -DestinationPath "$env:TEMP\nssm-extract" -Force
    Copy-Item "$env:TEMP\nssm-extract\nssm-2.24\win64\nssm.exe" $nssmExe -Force
    Remove-Item $zip, "$env:TEMP\nssm-extract" -Recurse -Force
    Write-Host "  [OK] nssm.exe ready" -ForegroundColor Green
} else {
    Write-Host "  [OK] nssm.exe exists" -ForegroundColor Green
}

# --- CONFIG FILE -------------------------------------------------------------
Write-Host "3/5 — Create app.ini" -ForegroundColor Cyan
$appIni = "$GiteaDir\custom\conf\app.ini"
New-Item -ItemType Directory -Force -Path (Split-Path $appIni) | Out-Null

if (-not (Test-Path $appIni)) {
@'
APP_NAME = DYD Git (Gitea)
RUN_USER = LOCAL SYSTEM
RUN_MODE = prod

[server]
PROTOCOL        = http
DOMAIN          = 103.124.94.58
HTTP_ADDR       = 127.0.0.1
HTTP_PORT       = 3000
ROOT_URL        = http://103.124.94.58:3000/
DISABLE_SSH     = true
OFFLINE_MODE    = false

[database]
DB_TYPE  = sqlite3
PATH     = C:/Gitea/data/gitea.db
LOG_SQL  = false

[repository]
ROOT = C:/Gitea/data/gitea-repositories

[log]
MODE      = file
LEVEL     = info
ROOT_PATH = C:/Gitea/log

[security]
INSTALL_LOCK    = false
; SECRET_KEY sẽ được tự sinh khi chạy lần đầu qua web installer

[service]
DISABLE_REGISTRATION               = true
REQUIRE_SIGNIN_VIEW                = true
ENABLE_NOTIFY_MAIL                 = false
REGISTER_EMAIL_CONFIRM             = false

[picture]
DISABLE_GRAVATAR = true

[actions]
ENABLED = true
'@ | Set-Content -Path $appIni -Encoding UTF8
    Write-Host "  [OK] app.ini created" -ForegroundColor Green
} else {
    Write-Host "  [OK] app.ini exists (skip)" -ForegroundColor Green
}

# --- INSTALL SERVICE --------------------------------------------------------
Write-Host "4/5 — Install NSSM service 'gitea'" -ForegroundColor Cyan
$existingService = Get-Service -Name 'gitea' -ErrorAction SilentlyContinue
if (-not $existingService) {
    & $nssmExe install gitea $giteaExe web --config "$appIni" --work-path "$GiteaDir"
    & $nssmExe set gitea AppStdout "$LogsDir\stdout.log"
    & $nssmExe set gitea AppStderr "$LogsDir\stderr.log"
    & $nssmExe set gitea AppRotateFiles 1
    & $nssmExe set gitea AppRotateBytes 10485760
    & $nssmExe set gitea DisplayName 'Gitea Service (DYD)'
    & $nssmExe set gitea Description 'Gitea self-hosted git + Actions for DYD project'
    & $nssmExe set gitea Start SERVICE_AUTO_START
    Write-Host "  [OK] Service installed" -ForegroundColor Green
} else {
    Write-Host "  [OK] Service 'gitea' exists" -ForegroundColor Green
}

# --- START -------------------------------------------------------------------
Write-Host "5/5 — Start Gitea service" -ForegroundColor Cyan
Start-Service gitea
Start-Sleep 5

$svc = Get-Service gitea
Write-Host "  Service status: $($svc.Status)" -ForegroundColor $(if ($svc.Status -eq 'Running') {'Green'} else {'Red'})

# --- Test HTTP ---------------------------------------------------------------
try {
    $r = Invoke-WebRequest 'http://127.0.0.1:3000' -UseBasicParsing -TimeoutSec 10
    Write-Host "  Gitea web responds: HTTP $($r.StatusCode)" -ForegroundColor Green
} catch {
    Write-Host "  [WARN] Gitea chưa response, check log: $LogsDir" -ForegroundColor Yellow
}

# --- SUMMARY -----------------------------------------------------------------
Write-Host ""
Write-Host "=========================================================" -ForegroundColor Green
Write-Host " Gitea installed" -ForegroundColor Green
Write-Host "=========================================================" -ForegroundColor Green
Write-Host ""
Write-Host "Next steps MANUAL:" -ForegroundColor Yellow
Write-Host "  1. Mở browser: http://103.124.94.58:3000"
Write-Host "  2. Complete installer wizard (SQLite OK, admin account)"
Write-Host "  3. Sau khi setup: Site Admin → Disable Registration"
Write-Host "  4. Tạo repo 'DYD' và push code"
Write-Host "  5. Site Admin → Actions → Runner Management → Create Runner"
Write-Host "     → copy registration token → chạy 05-install-act-runner.ps1"
Write-Host ""
Write-Host "Config file: $appIni"
Write-Host "Logs:        $LogsDir"
