# EENE Dashboard -> Gitea upload
# Run: Gitea업로드.bat  or  powershell -ExecutionPolicy Bypass -File scripts\gitea-upload.ps1

$ErrorActionPreference = 'Stop'
$projectRoot = Split-Path $PSScriptRoot -Parent
$pubKeyPath = Join-Path $env:USERPROFILE '.ssh\id_ed25519_eene_dashboard.pub'

Write-Host ''
Write-Host '=== EENE Dashboard Gitea upload ===' -ForegroundColor Cyan
Write-Host ''

if (-not (Test-Path $pubKeyPath)) {
  Write-Host '[ERROR] Deploy key not found. Run:' -ForegroundColor Red
  Write-Host '  ssh-keygen -t ed25519 -C eene_dashboard-deploy -f $env:USERPROFILE\.ssh\id_ed25519_eene_dashboard -N ""'
  exit 1
}

Write-Host '[1/4] Deploy key (paste this line in Gitea -> Settings -> Deploy Keys):' -ForegroundColor Yellow
Write-Host ''
Get-Content $pubKeyPath
Write-Host ''
$ok = Read-Host 'Registered deploy key on Gitea? (y/n)'
if ($ok -ne 'y' -and $ok -ne 'Y') {
  Write-Host 'Register the key on Gitea, then run again.' -ForegroundColor Yellow
  exit 0
}

Write-Host ''
Write-Host '[2/4] SSH test...' -ForegroundColor Yellow
$keyPath = Join-Path $env:USERPROFILE '.ssh\id_ed25519_eene_dashboard'
$fp = ssh-keygen -lf $pubKeyPath 2>$null
if ($fp) { Write-Host "      Key fingerprint: $fp" -ForegroundColor DarkGray }
$giteaHost = '172.16.10.175'
$giteaPort = 222
$giteaRepo = 'RyuWonJun/eene_dashboard.git'
$sshConfig = Join-Path $env:USERPROFILE '.ssh\config'

$sshArgs = @(
  '-i', $keyPath,
  '-T', "git@${giteaHost}",
  '-p', $giteaPort,
  '-o', 'IdentitiesOnly=yes',
  '-o', 'ConnectTimeout=10',
  '-o', 'StrictHostKeyChecking=accept-new'
)
if (Test-Path $sshConfig) {
  $sshArgs = @('-F', $sshConfig) + $sshArgs
}

$prevEap = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
$sshLines = [System.Collections.Generic.List[string]]::new()
try {
  & ssh @sshArgs 2>&1 | ForEach-Object { [void]$sshLines.Add("$($_)".Trim()) }
} finally {
  $ErrorActionPreference = $prevEap
}
$test = ($sshLines | Where-Object { $_ }) -join "`n"
if (-not $test) { $test = '' }

if ($test) {
  Write-Host $test
} else {
  Write-Host '      (no SSH message — checking exit code)' -ForegroundColor DarkGray
}
if ($test -match 'Permission denied') {
  Write-Host ''
  Write-Host '[ERROR] Gitea rejected this key.' -ForegroundColor Red
  Write-Host "  SSH port $giteaPort failed. Gitea SSH is often NOT port 22." -ForegroundColor Yellow
  Write-Host '  Check Gitea web -> SSH clone URL for the correct port.' -ForegroundColor Yellow
  Write-Host '  Fix on Gitea web:' -ForegroundColor Yellow
  Write-Host '    1. eene_dashboard -> Settings -> Deploy Keys' -ForegroundColor Yellow
  Write-Host '    2. Delete old keys' -ForegroundColor Yellow
  Write-Host '    3. Add key: paste the ssh-ed25519 line from step [1/4] EXACTLY' -ForegroundColor Yellow
  Write-Host '    4. Enable write access, then save' -ForegroundColor Yellow
  Write-Host '  Or: Gitea user Settings -> SSH Keys (same public key line)' -ForegroundColor Yellow
  exit 1
}
if ($test -notmatch 'successfully authenticated') {
  if ($LASTEXITCODE -eq 0 -and -not $test) {
    Write-Host '      SSH OK (exit 0)' -ForegroundColor Green
  } else {
    Write-Host ''
    Write-Host '[ERROR] Unexpected SSH response. Check port and deploy key.' -ForegroundColor Red
    if ($LASTEXITCODE -ne 0) {
      Write-Host "      ssh exit code: $LASTEXITCODE" -ForegroundColor Yellow
    }
    exit 1
  }
} else {
  Write-Host '      SSH OK' -ForegroundColor Green
}

Set-Location $projectRoot

Write-Host ''
Write-Host '[3/4] git remote gitea...' -ForegroundColor Yellow
$giteaUrl = "ssh://git@${giteaHost}:${giteaPort}/${giteaRepo}"
$env:GIT_SSH_COMMAND = "ssh -F `"$sshConfig`""
$remotes = @(git remote 2>$null)
if ($remotes -contains 'gitea') {
  git remote set-url gitea $giteaUrl
} else {
  git remote add gitea $giteaUrl
}

Write-Host ''
Write-Host '[4/4] commit and push...' -ForegroundColor Yellow

git add -A
$status = git status --porcelain
if ($status) {
  git commit -m 'EENE Dashboard upload to Gitea'
} else {
  Write-Host '      No changes to commit, push only.' -ForegroundColor DarkGray
}

git push -u gitea main
if ($LASTEXITCODE -ne 0) {
  Write-Host ''
  Write-Host '[ERROR] push failed. Check branch: git branch' -ForegroundColor Red
  exit 1
}

Write-Host ''
Write-Host '=== Done ===' -ForegroundColor Green
Write-Host 'Included: code, data/postgres, uploads, data/seed (backend/.env excluded — auto-created on start).' -ForegroundColor DarkGray
Write-Host ''
