#!/bin/bash
SERVER_IP="47.253.147.187"
SERVER_USER="root"
SERVER_PASS="5H0FuZ:2s0q)Lx"

/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 /www/server/panel/vhost/nginx/ccdw.xyz.conf; \
    echo 'Certificate verified. Applying config...'; \
else \
    echo 'Certificate NOT found, trying install again...'; \
    apt-get update && apt-get install -y certbot; \
    /etc/init.d/nginx stop; \
    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 /www/server/panel/vhost/nginx/ccdw.xyz.conf; \
    fi; \
fi\r"

send "echo '--- RESTARTING NGINX ---'\r"
send "/etc/init.d/nginx start\r"
send "/etc/init.d/nginx reload\r"
send "nginx -t\r"

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

send "exit\r"
expect eof
EOF
