#Requires -Version 5.1
<#
.SYNOPSIS
  Enable Settings → Software Updates on production (git pull in /opt/cnperp).

.PARAMETER GitHubToken
  Read-only PAT for private repo (or set $GitHubToken in production.local.ps1).

.PARAMETER UseGitCredential
  Read token from Windows Git Credential Manager (current user's github.com login).

.EXAMPLE
  cd c:\dev\cnperp-dimensions\deploy\hetzner
  .\Setup-GitUpdatesOnProduction.ps1 -UseGitCredential
#>
param(
    [string]$GitHubToken = "",
    [switch]$UseGitCredential
)

$ErrorActionPreference = "Stop"
$Here = $PSScriptRoot
$RepoRoot = Split-Path (Split-Path $Here -Parent) -Parent
$LocalConfig = Join-Path $Here "production.local.ps1"
if (Test-Path $LocalConfig) { . $LocalConfig }

if (-not $GitHubToken -and $UseGitCredential) {
    try {
        $credInput = "protocol=https`nhost=github.com`n`n"
        $credOut = $credInput | git credential-manager get 2>$null
        foreach ($line in ($credOut -split "`n")) {
            if ($line -match '^password=(.+)$') {
                $GitHubToken = $Matches[1].Trim()
                break
            }
        }
    } catch { }
}
if (-not $GitHubToken -and (Get-Variable -Name GitHubToken -Scope Script -ErrorAction SilentlyContinue)) {
    # from production.local.ps1 dot-source
}
if (-not $GitHubToken) {
    Write-Host "No GitHub token. Use -UseGitCredential, -GitHubToken, or set `$GitHubToken in production.local.ps1" -ForegroundColor Yellow
}

$ServerIp = if ($ServerIp) { $ServerIp } else { "178.105.218.193" }
$SshUser = if ($SshUser) { $SshUser } else { "root" }
$deployKey = (& "$Here\_prepare-deploy-key.ps1" | Select-Object -Last 1).Trim()
$sshArgs = @("-i", $deployKey, "-o", "IdentitiesOnly=yes", "-o", "BatchMode=yes", "-o", "ServerAliveInterval=30")
$scpArgs = @("-i", $deployKey, "-o", "IdentitiesOnly=yes", "-o", "BatchMode=yes")

$scriptLocal = Join-Path $Here "enable-git-updates.sh"
$autoUpdate = Join-Path $RepoRoot "deploy\auto_update.sh"

Write-Host "Uploading enable-git-updates.sh + auto_update.sh..." -ForegroundColor Cyan
scp @scpArgs $scriptLocal "${SshUser}@${ServerIp}:/tmp/enable-git-updates.sh"
scp @scpArgs $autoUpdate "${SshUser}@${ServerIp}:/tmp/auto_update.sh"

$tokenExport = ""
if ($GitHubToken) {
    $tokenExport = "export GITHUB_TOKEN='$($GitHubToken -replace "'", "'\''")';"
}

$remote = @"
set -e
cp /tmp/enable-git-updates.sh /opt/cnperp/deploy/hetzner/enable-git-updates.sh
cp /tmp/auto_update.sh /opt/cnperp/deploy/auto_update.sh
chmod +x /opt/cnperp/deploy/hetzner/enable-git-updates.sh /opt/cnperp/deploy/auto_update.sh
chown cnperp:cnperp /opt/cnperp/deploy/auto_update.sh /opt/cnperp/deploy/hetzner/enable-git-updates.sh
sed -i 's/\r$//' /opt/cnperp/deploy/hetzner/enable-git-updates.sh /opt/cnperp/deploy/auto_update.sh
$tokenExport bash /opt/cnperp/deploy/hetzner/enable-git-updates.sh
"@ -replace "`r", ""

Write-Host "Running enable-git-updates on ${SshUser}@${ServerIp}..." -ForegroundColor Cyan
ssh @sshArgs "${SshUser}@${ServerIp}" $remote
$code = $LASTEXITCODE
Remove-Item -Force $deployKey, "$deployKey.pub" -ErrorAction SilentlyContinue
if ($code -ne 0) { exit $code }

Write-Host "`nDone. Test in ERP: Settings → Software Updates → Check for updates" -ForegroundColor Green
