@echo off
chcp 65001 >nul
echo ===============================================
echo SSH Key Setup for Server Deployment
echo ===============================================

set "SERVER_IP=10.26.252.51"
set "SERVER_USER=root"

echo [INFO] Setting up SSH key authentication for %SERVER_USER%@%SERVER_IP%
echo.

REM Check if SSH key exists
if not exist "%USERPROFILE%\.ssh\id_rsa.pub" (
    echo [INFO] SSH key not found. Generating new SSH key...
    ssh-keygen -t rsa -b 4096 -f "%USERPROFILE%\.ssh\id_rsa" -N ""
    if !ERRORLEVEL! neq 0 (
        echo [ERROR] Failed to generate SSH key
        pause
        exit /b 1
    )
    echo [SUCCESS] SSH key generated
)

echo.
echo [INFO] Copying SSH key to server...
echo [INFO] You will be prompted for the server password
echo.

type "%USERPROFILE%\.ssh\id_rsa.pub" | ssh %SERVER_USER%@%SERVER_IP% "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys && echo '[SUCCESS] SSH key installed'"

if !ERRORLEVEL! neq 0 (
    echo [ERROR] Failed to copy SSH key
    echo.
    echo Please ensure:
    echo - Server is accessible at %SERVER_IP%
    echo - You have the correct password for %SERVER_USER%
    echo - SSH service is running on the server
    pause
    exit /b 1
)

echo.
echo ===============================================
echo [SUCCESS] SSH Key Setup Complete!
echo ===============================================
echo.
echo Testing connection...
ssh -o BatchMode=yes -o ConnectTimeout=10 %SERVER_USER%@%SERVER_IP% "echo '[SUCCESS] SSH key authentication working!'"

if !ERRORLEVEL! equ 0 (
    echo.
    echo You can now run deploy-only.bat without password
) else (
    echo [WARN] Key authentication test failed
    echo Please try running this script again
)

pause