$ErrorActionPreference = "Stop"

$Key = Join-Path $env:USERPROFILE ".ssh\durakometr_release"
$Pub = "$Key.pub"
$Server = "root@5.188.21.226"

$SshDir = Split-Path $Key -Parent

if (-not (Test-Path $SshDir)) {
    New-Item -ItemType Directory -Path $SshDir | Out-Null
}

if (-not (Test-Path $Key)) {
    Write-Host "Creating SSH key for Durakometr release..."

    & ssh-keygen.exe -t ed25519 -f $Key -C "durakometr-android-studio" -N ""

    if ($LASTEXITCODE -ne 0) {
        throw "ssh-keygen failed"
    }
}

if (-not (Test-Path $Pub)) {
    throw "Public key not found: $Pub"
}

Write-Host ""
Write-Host "The VPS will ask for the root password one time."
Write-Host ""

$PublicKey = (Get-Content $Pub -Raw).Trim()

if ([string]::IsNullOrWhiteSpace($PublicKey)) {
    throw "Public key is empty"
}

$RemoteCommand = @"
umask 077
mkdir -p ~/.ssh
touch ~/.ssh/authorized_keys
grep -qxF '$PublicKey' ~/.ssh/authorized_keys || echo '$PublicKey' >> ~/.ssh/authorized_keys
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
"@

& ssh.exe $Server $RemoteCommand

if ($LASTEXITCODE -ne 0) {
    throw "Failed to install SSH public key"
}

Write-Host ""
Write-Host "Testing passwordless SSH..."

& ssh.exe -i $Key -o BatchMode=yes -o ConnectTimeout=10 $Server "echo RELEASE_SSH_OK"

if ($LASTEXITCODE -ne 0) {
    throw "SSH key login test failed"
}

Write-Host ""
Write-Host "SSH setup complete."
