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

/usr/bin/expect <<EOF
set timeout 120
spawn ssh -o StrictHostKeyChecking=no $SERVER_USER@$SERVER_IP
expect {
    "password:" { send "$SERVER_PASS\r" }
    "yes/no" { send "yes\r"; exp_continue }
}
expect "#"

send "ls -l /etc/letsencrypt/live/ccdw.xyz/fullchain.pem\r"

# 使用 test 命令代替 [] 避免 Tcl 解析错误
send "if test -f /etc/letsencrypt/live/ccdw.xyz/fullchain.pem; then \
    mv /tmp/ccdw_full.conf /etc/nginx/sites-available/ccdw.xyz.conf && ln -sf /etc/nginx/sites-available/ccdw.xyz.conf /etc/nginx/sites-enabled/ccdw.xyz.conf; \
    echo 'Certificate verified. Applying config...'; \
else \
    echo 'Certificate NOT found, trying install again...'; \
    apt-get update && apt-get install -y certbot; \
    systemctl stop nginx; \
    killall nginx; \
    certbot certonly --standalone -d ccdw.xyz -d www.ccdw.xyz --email bob.yuxinyang@gmail.com --agree-tos --non-interactive; \
    if test -f /etc/letsencrypt/live/ccdw.xyz/fullchain.pem; then \
        mv /tmp/ccdw_full.conf /etc/nginx/sites-available/ccdw.xyz.conf && ln -sf /etc/nginx/sites-available/ccdw.xyz.conf /etc/nginx/sites-enabled/ccdw.xyz.conf; \
    fi; \
fi\r"

send "echo '--- RESTARTING NGINX ---'\r"
send "systemctl start nginx\r"
send "systemctl reload nginx\r"
send "nginx -t\r"

send "echo '--- VERIFYING ---'\r"
send "curl -I https://ccdw.xyz\r"

send "exit\r"
expect eof
EOF
