#!/bin/bash

SERVER_IP="45.61.60.10"
SERVER_USER="root"
SERVER_PASS="UQb9TgSwC@vwhEM"

GREEN='\033[0;32m'
NC='\033[0m'

echo -e "${GREEN}=== 开始配置远程服务器环境 ===${NC}"

# 使用 expect 登录远程服务器并执行初始化
/usr/bin/expect <<EOF
set timeout 600
spawn ssh -o StrictHostKeyChecking=no $SERVER_USER@$SERVER_IP

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

expect "#"

# 1. 更新系统并安装基础依赖
send "echo '--- 1. UPDATING PACKAGES & SYSTEM ---'\r"
expect "#"
send "apt-get update && apt-get install -y curl gnupg git build-essential nginx certbot python3-certbot-nginx\r"
expect "#"

# 2. 安装 Node.js 22 LTS (via NodeSource)
send "echo '--- 2. INSTALLING NODE.JS 22 ---'\r"
expect "#"
send "curl -fsSL https://deb.nodesource.com/setup_22.x | bash -\r"
expect "#"
send "apt-get install -y nodejs\r"
expect "#"

# 3. 验证 Node/NPM 并安装 PM2
send "echo '--- 3. INSTALLING PM2 ---'\r"
expect "#"
send "node -v && npm -v\r"
expect "#"
send "npm install -g pm2 --registry=https://registry.npmmirror.com\r"
expect "#"

# 4. 创建部署目录
send "echo '--- 4. CREATING DEPLOYMENT DIR ---'\r"
expect "#"
send "mkdir -p /var/www/ccdw-website\r"
expect "#"
send "chown -R root:root /var/www/ccdw-website\r"
expect "#"

# 5. 验证安装
send "echo '--- 5. VERIFYING INSTALLATIONS ---'\r"
expect "#"
send "command -v node && command -v npm && command -v pm2 && command -v nginx\r"
expect "#"

send "exit\r"
expect eof
EOF

echo -e "${GREEN}=== 服务器环境配置完成！ ===${NC}"
