# ============================================================================
# 05 — Install act_runner (Gitea Actions runner) as Windows service
# PREREQUISITE:
#   1. Gitea đã chạy (04-install-gitea.ps1)
#   2. Đã lấy registration token từ Gitea:
#      Site Admin → Actions → Runner Management → Create new Runner → Copy token
# Usage:
#   .\05-install-act-runner.ps1 -Token <registration-token>
# ============================================================================

param(
    [Parameter(Mandatory=$true)]
    [string]$Token,

    [string]$GiteaUrl   = 'http://127.0.0.1:3000',
    [string]$RunnerName = 'dyd-windows-runner',
    [string]$Labels     = 'windows:host,windows-latest:host'
)

#Requires -RunAsAdministrator

$ErrorActionPreference = 'Stop'
$RunnerDir = 'C:\Tools\act_runner'
$NSSM      = 'C:\Tools\nssm\nssm.exe'

if (-not (Test-Path $NSSM)) {
    Write-Error "NSSM chưa cài. Chạy 04-install-gitea.ps1 trước."
    exit 1
}

# --- DOWNLOAD ---------------------------------------------------------------
Write-Host "1/4 — Download act_runner" -ForegroundColor Cyan
New-Item -ItemType Directory -Force -Path $RunnerDir | Out-Null

$runnerExe = "$RunnerDir\act_runner.exe"
if (-not (Test-Path $runnerExe)) {
    $url = 'https://dl.gitea.com/act_runner/0.2.11/act_runner-0.2.11-windows-amd64.exe'
    Invoke-WebRequest -Uri $url -OutFile $runnerExe
    Write-Host "  [OK] downloaded" -ForegroundColor Green
}

# --- REGISTER ---------------------------------------------------------------
Write-Host "2/4 — Register with Gitea" -ForegroundColor Cyan
Set-Location $RunnerDir
if (-not (Test-Path "$RunnerDir\.runner")) {
    & $runnerExe register --no-interactive `
        --instance $GiteaUrl `
        --token $Token `
        --name $RunnerName `
        --labels $Labels
    if ($LASTEXITCODE -ne 0) {
        Write-Error "Register failed. Check token + Gitea URL."
        exit 1
    }
    Write-Host "  [OK] Registered as $RunnerName" -ForegroundColor Green
} else {
    Write-Host "  [OK] Already registered (.runner exists)" -ForegroundColor Green
}

# --- CONFIG -----------------------------------------------------------------
Write-Host "3/4 — Generate config.yaml" -ForegroundColor Cyan
$cfgFile = "$RunnerDir\config.yaml"
if (-not (Test-Path $cfgFile)) {
    & $runnerExe generate-config | Set-Content $cfgFile -Encoding UTF8
    Write-Host "  [OK] config.yaml ready — edit nếu cần tùy chỉnh" -ForegroundColor Green
}

# --- SERVICE ----------------------------------------------------------------
Write-Host "4/4 — Install NSSM service 'act_runner'" -ForegroundColor Cyan
$svc = Get-Service -Name 'act_runner' -ErrorAction SilentlyContinue
if (-not $svc) {
    & $NSSM install act_runner $runnerExe daemon --config "$cfgFile"
    & $NSSM set act_runner AppDirectory $RunnerDir
    & $NSSM set act_runner AppStdout "$RunnerDir\runner-stdout.log"
    & $NSSM set act_runner AppStderr "$RunnerDir\runner-stderr.log"
    & $NSSM set act_runner AppRotateFiles 1
    & $NSSM set act_runner AppRotateBytes 10485760
    & $NSSM set act_runner DisplayName 'Gitea Actions Runner (DYD)'
    & $NSSM set act_runner Start SERVICE_AUTO_START
    Write-Host "  [OK] Service installed" -ForegroundColor Green
}

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

# --- DONE -------------------------------------------------------------------
Write-Host ""
Write-Host "=========================================================" -ForegroundColor Green
Write-Host " act_runner ready — Gitea Actions sẵn sàng" -ForegroundColor Green
Write-Host "=========================================================" -ForegroundColor Green
Write-Host ""
Write-Host "Verify:"
Write-Host "  Gitea UI → Site Admin → Actions → Runner — phải thấy '$RunnerName' online"
Write-Host ""
Write-Host "Labels:   $Labels"
Write-Host "Logs:     $RunnerDir\runner-*.log"
