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

# 1. Upload Nginx config
/usr/bin/expect <<EOF
set timeout 30
spawn scp -o StrictHostKeyChecking=no ccdw.xyz.conf $SERVER_USER@$SERVER_IP:/etc/nginx/sites-available/ccdw.xyz.conf
expect {
    "password:" { send "$SERVER_PASS\r" }
    "yes/no" { send "yes\r"; exp_continue }
}
expect eof
EOF

# 2. SSH actions
/usr/bin/expect <<EOF
set timeout 60
spawn ssh -o StrictHostKeyChecking=no $SERVER_USER@$SERVER_IP

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

expect "#"

# Reload Nginx
send "echo '--- RELOADING NGINX STATUS ---'\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"

# Check Node App
send "echo '--- CHECKING NODE APP ---'\r"
send "cd /var/www/ccdw-website/server\r"
# Force install production deps again just in case
send "npm install --omit=dev --registry=https://registry.npmmirror.com\r"
send "pm2 restart ccdw-server\r"
send "sleep 3\r"
send "pm2 list\r"
send "pm2 logs ccdw-server --lines 20 --nostream\r"

# Check ports again
send "netstat -tulpn | grep 3001\r"

send "exit\r"
expect eof
EOF
