#!/bin/bash
SERVER_IP="45.61.60.10"
SERVER_USER="root"
SERVER_PASS="UQb9TgSwC@vwhEM"

/usr/bin/expect <<EOF
set timeout 180
spawn ssh -o StrictHostKeyChecking=no $SERVER_USER@$SERVER_IP

expect {
    "password:" { send "$SERVER_PASS\r" }
    "yes/no" { send "yes\r"; exp_continue }
}

expect "#"

# 1. Check Node binaries
send "echo '--- CHECKING NODE BINARIES ---'\r"
send "which node\r"
send "which npm\r"
send "which npx\r"

# 2. Finish backend deployment
send "echo '--- FINISHING BACKEND DEPLOYMENT ---'\r"
send "cd /var/www/ccdw-website/server\r"
send "npm install --omit=dev --registry=https://registry.npmmirror.com\r"
send "npm install -g pm2 --registry=https://registry.npmmirror.com\r"

# Start App
send "echo '--- STARTING APP ---'\r"
send "pm2 delete ccdw-server 2>/dev/null\r"
send "pm2 start index.js --name ccdw-server\r"
send "pm2 save\r"

# 3. Create Nginx Config (HTTP)
send "echo '--- CREATING NGINX CONFIG ---'\r"
send "cat > /etc/nginx/sites-available/ccdw.xyz.conf <<ENDCONF
server {
    listen 80;
    server_name ccdw.xyz www.ccdw.xyz;
    
    access_log /var/log/nginx/ccdw.xyz.log;
    error_log /var/log/nginx/ccdw.xyz.error.log;

    location / {
        proxy_pass http://127.0.0.1:3001;
        proxy_set_header Host \\\$host;
        proxy_set_header X-Real-IP \\\$remote_addr;
        proxy_set_header X-Forwarded-For \\\$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \\\$scheme;
    }
}
ENDCONF\r"

# 4. Reload Nginx
send "echo '--- RELOADING NGINX ---'\r"
send "nginx -t\r"
send "ln -sf /etc/nginx/sites-available/ccdw.xyz.conf /etc/nginx/sites-enabled/ccdw.xyz.conf\r"
send "systemctl reload nginx\r"

# 5. Check URL access
send "echo '--- CHECKING ACCESS ---'\r"
send "curl -I http://127.0.0.1:3001\r"
send "curl -I -H 'Host: ccdw.xyz' http://127.0.0.1\r"

send "exit\r"
expect eof
EOF
