# Register Gitea Actions runner on VPS Windows Server.
# Can be shared with VIETREPORT (runner serves multiple repos via labels).
#
# Usage (admin PowerShell):
#   .\setup-gitea-runner.ps1 -RegistrationToken 'xxxx' -RunnerName 'vps-win-01'
#
# Get RegistrationToken from:
#   https://git.baocaogiaoduc.vn/-/admin/actions/runners (admin only)
#   or per-repo: https://git.baocaogiaoduc.vn/vietreport-admin/solution-erp/settings/actions/runners

param(
    [Parameter(Mandatory=$true)] [string]$RegistrationToken,
    [string]$RunnerName = "vps-win-$(Get-Date -Format 'yyyyMMdd')",
    [string]$InstallDir = "C:\gitea-runner",
    [string]$GiteaUrl = "https://git.baocaogiaoduc.vn",
    [string]$Labels = "windows-latest,self-hosted,windows,x64"
)

$ErrorActionPreference = 'Stop'

# ===================== 1. Download runner =====================
$RunnerExe = Join-Path $InstallDir "act_runner.exe"

if (-not (Test-Path $RunnerExe)) {
    Write-Host "==> Download Gitea act_runner" -ForegroundColor Cyan
    if (-not (Test-Path $InstallDir)) { New-Item -ItemType Directory -Force -Path $InstallDir | Out-Null }

    # Latest release from Gitea CDN
    $url = "https://dl.gitea.com/act_runner/act_runner-windows-amd64.exe"
    Invoke-WebRequest -Uri $url -OutFile $RunnerExe -UseBasicParsing
    Write-Host "  Downloaded $RunnerExe"
}

# ===================== 2. Register =====================
Set-Location $InstallDir

if (-not (Test-Path (Join-Path $InstallDir ".runner"))) {
    Write-Host ""
    Write-Host "==> Register with Gitea $GiteaUrl" -ForegroundColor Cyan
    & $RunnerExe register `
        --no-interactive `
        --instance $GiteaUrl `
        --token $RegistrationToken `
        --name $RunnerName `
        --labels $Labels
    if ($LASTEXITCODE -ne 0) {
        Write-Error "Register fail. Check: token correct? GiteaUrl reachable? Runner name '$RunnerName' already used?"
        exit 1
    }
    Write-Host "  Registered as '$RunnerName'"
} else {
    Write-Host "  Runner already registered (.runner file exists)"
}

# ===================== 3. Install as Windows service =====================
$ServiceName = "gitea-runner"
$svc = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
if (-not $svc) {
    Write-Host ""
    Write-Host "==> Install Windows service" -ForegroundColor Cyan
    # act_runner has no built-in service install - use sc.exe
    sc.exe create $ServiceName binPath= "`"$RunnerExe`" daemon --config `"$InstallDir\config.yml`"" start= auto DisplayName= "Gitea Actions Runner"
    Start-Service $ServiceName
    Write-Host "  Service '$ServiceName' installed + started"
} else {
    if ($svc.Status -ne 'Running') {
        Start-Service $ServiceName
        Write-Host "  Service started"
    } else {
        Write-Host "  Service already running"
    }
}

Write-Host ""
Write-Host "[OK] Runner setup DONE" -ForegroundColor Green
Write-Host "   Check on Gitea: $GiteaUrl/-/admin/actions/runners (admin) or repo settings > Actions > Runners"
Write-Host "   Labels: $Labels"
Write-Host "   Log: Get-Content '$InstallDir\log.txt' -Tail 50 -Wait"
