# =============================================================================
# WEBMoney - Configuração Inicial SSH (Executar apenas UMA vez)
# =============================================================================
# Copia a chave pública SSH para o servidor, permitindo conexões sem senha
# =============================================================================

$Server = "213.165.93.60"
$User = "root"
$Password = "Master9354"

Write-Host ""
Write-Host "╔═══════════════════════════════════════════════════════════════╗" -ForegroundColor Cyan
Write-Host "║       CONFIGURAÇÃO SSH SEM SENHA - WebMoney                   ║" -ForegroundColor Cyan
Write-Host "╚═══════════════════════════════════════════════════════════════╝" -ForegroundColor Cyan
Write-Host ""

# Verificar se já existe chave SSH
$sshKeyPath = "$env:USERPROFILE\.ssh\id_rsa.pub"

if (-not (Test-Path $sshKeyPath)) {
    Write-Host "Gerando par de chaves SSH..." -ForegroundColor Yellow
    ssh-keygen -t rsa -b 4096 -f "$env:USERPROFILE\.ssh\id_rsa" -N '""' -q
    Write-Host "✓ Chaves geradas" -ForegroundColor Green
}

$pubKey = Get-Content $sshKeyPath

Write-Host ""
Write-Host "Servidor: $Server" -ForegroundColor White
Write-Host "Usuário:  $User" -ForegroundColor White
Write-Host ""
Write-Host "A contraseña do servidor será solicitada: " -NoNewline -ForegroundColor Yellow
Write-Host $Password -ForegroundColor Red
Write-Host ""

# Comando para adicionar a chave no servidor
$sshCommand = "mkdir -p ~/.ssh && chmod 700 ~/.ssh && echo '$pubKey' >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys && echo 'OK'"

Write-Host "Copiando chave pública para o servidor..." -ForegroundColor Yellow
Write-Host "(Digite a senha quando solicitado)" -ForegroundColor Gray
Write-Host ""

# Executar
$result = ssh -o StrictHostKeyChecking=no "$User@$Server" $sshCommand

if ($result -eq "OK") {
    Write-Host ""
    Write-Host "╔═══════════════════════════════════════════════════════════════╗" -ForegroundColor Green
    Write-Host "║              ✓ SSH CONFIGURADO COM SUCESSO!                   ║" -ForegroundColor Green
    Write-Host "╚═══════════════════════════════════════════════════════════════╝" -ForegroundColor Green
    Write-Host ""
    Write-Host "Agora você pode conectar sem senha:" -ForegroundColor White
    Write-Host "  ssh root@$Server" -ForegroundColor Cyan
    Write-Host ""
    Write-Host "Os scripts de deploy funcionarão automaticamente." -ForegroundColor White
    Write-Host ""
} else {
    Write-Host ""
    Write-Host "⚠ Algo pode ter dado errado. Teste a conexão:" -ForegroundColor Yellow
    Write-Host "  ssh root@$Server" -ForegroundColor Cyan
    Write-Host ""
}
