#!/bin/bash
set -e

# ====================== 定制配置区（可直接修改） ======================
DB_USER="yexuan"
DB_PASS="SB111111"
DB_NAME="touchgal"
PROJECT_DIR="/www/wwwroot/gal.186.baby"
PORT="3000"
DOMAIN="186.baby"
GIT_REPO="https://github.com/KUN1007/kun-touchgal-next.git"
# =====================================================================

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# 欢迎信息
echo -e "${GREEN}===== TouchGal 一站式部署脚本（含 HTTPS 配置）=====${NC}"
echo -e "${YELLOW}配置：域名=${DOMAIN} | 数据库用户=${DB_USER} | 端口=${PORT}${NC}\n"

# 0. 检测 CentOS 版本
echo -e "${YELLOW}[0/12] 检测系统版本${NC}"
OS_VERSION=$(cat /etc/centos-release | grep -oE '[0-9]+\.' | cut -d. -f1 | head -n1)
if [ "$OS_VERSION" -lt 7 ]; then
    echo -e "${RED}错误：仅支持 CentOS 7/8，当前版本不兼容！${NC}"
    exit 1
fi
echo -e "${GREEN}当前系统 CentOS ${OS_VERSION}，符合要求${NC}"

# 1. 安装系统基础依赖 + Nginx + Certbot
echo -e "${YELLOW}[1/12] 安装系统依赖（含 Certbot SSL 工具）${NC}"
yum update -y
yum install -y epel-release git wget curl postgresql-server postgresql-contrib redis firewalld vim nginx certbot python3-certbot-nginx -y

# 2. 启动所有服务并开机自启
echo -e "${YELLOW}[2/12] 启动核心服务${NC}"
systemctl start redis && systemctl enable redis
systemctl start firewalld && systemctl enable firewalld
systemctl start nginx && systemctl enable nginx
# 放行端口（80/443 为 HTTP/HTTPS 必备）
firewall-cmd --permanent --add-port=${PORT}/tcp
firewall-cmd --permanent --add-service=http --add-service=https
firewall-cmd --reload

# 3. 安装 Node.js 20.x + pnpm
echo -e "${YELLOW}[3/12] 安装 Node.js 和 pnpm${NC}"
curl -fsSL https://rpm.nodesource.com/setup_20.x | bash -
yum install -y nodejs
npm install -g pnpm

# 4. 初始化 PostgreSQL
echo -e "${YELLOW}[4/12] 配置 PostgreSQL 数据库${NC}"
postgresql-setup initdb
systemctl start postgresql && systemctl enable postgresql

# 5. 创建数据库和用户（覆盖旧配置）
echo -e "${YELLOW}[5/12] 创建定制数据库用户${NC}"
su - postgres -c "psql -c \"DROP USER IF EXISTS ${DB_USER}; CREATE USER ${DB_USER} WITH PASSWORD '${DB_PASS}'; DROP DATABASE IF EXISTS ${DB_NAME}; CREATE DATABASE ${DB_NAME} OWNER ${DB_USER}; REVOKE ALL PRIVILEGES ON DATABASE ${DB_NAME} FROM postgres;\""

# 6. 拉取项目代码
echo -e "${YELLOW}[6/12] 拉取 TouchGal 项目代码${NC}"
mkdir -p $(dirname ${PROJECT_DIR})
git clone ${GIT_REPO} ${PROJECT_DIR} || { echo -e "${RED}Git 拉取失败${NC}"; exit 1; }
cd ${PROJECT_DIR}

# 7. 生成 .env 文件（无 SMTP，绑定 HTTPS 域名）
echo -e "${YELLOW}[7/12] 生成环境配置文件${NC}"
cat > .env << EOF
# 数据库配置
KUN_DATABASE_URL = "postgresql://${DB_USER}:${DB_PASS}@localhost:5432/${DB_NAME}?schema=public"

# 网站 HTTPS 域名配置
KUN_VISUAL_NOVEL_SITE_URL = "https://${DOMAIN}"
NEXT_PUBLIC_KUN_PATCH_ADDRESS_DEV = "https://${DOMAIN}"
NEXT_PUBLIC_KUN_PATCH_ADDRESS_PROD = "https://${DOMAIN}"

# Redis 配置
REDIS_HOST = '127.0.0.1'
REDIS_PORT = '6379'

# JWT 配置
JWT_ISS = 'touchgal'
JWT_AUD = 'touchgal_admin'
JWT_SECRET = 'moemoekungalgamekunisthecutest!chinorensukiazkhx'

# 运行环境
NODE_ENV = "production"

# S3 存储配置（示例）
KUN_VISUAL_NOVEL_S3_STORAGE_ACCESS_KEY_ID = "kkkkkkkkkkkkkkkkkkkkkkkkkkkk"
KUN_VISUAL_NOVEL_S3_STORAGE_SECRET_ACCESS_KEY = "kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk"
KUN_VISUAL_NOVEL_S3_STORAGE_BUCKET_NAME = "kun"
KUN_VISUAL_NOVEL_S3_STORAGE_ENDPOINT = "https://moyu.moe"
KUN_VISUAL_NOVEL_S3_STORAGE_REGION = "us-west-001"
NEXT_PUBLIC_KUN_VISUAL_NOVEL_S3_STORAGE_URL = "https://touchgal-patch.moyu.moe"

# 图床配置
KUN_VISUAL_NOVEL_IMAGE_BED_HOST = "touchgal-image.${DOMAIN}"
KUN_VISUAL_NOVEL_IMAGE_BED_URL = "https://touchgal-image.${DOMAIN}"
EOF

# 8. 配置 Nginx 反向代理（先 HTTP，后续自动升级 HTTPS）
echo -e "${YELLOW}[8/12] 配置 Nginx 反向代理${NC}"
cat > /etc/nginx/conf.d/${DOMAIN}.conf << EOF
server {
    listen 80;
    server_name ${DOMAIN} www.${DOMAIN};

    location / {
        proxy_pass http://127.0.0.1:${PORT};
        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;
    }

    proxy_connect_timeout 600;
    proxy_send_timeout 600;
    proxy_read_timeout 600;
}
EOF
# 验证 Nginx 配置
nginx -t && systemctl restart nginx

# 9. 申请 Let's Encrypt 免费 SSL 证书（自动配置 Nginx）
echo -e "${YELLOW}[9/12] 申请免费 SSL 证书并配置 HTTPS${NC}"
certbot --nginx -d ${DOMAIN} -d www.${DOMAIN} --non-interactive --agree-tos --email admin@${DOMAIN}

# 10. 安装项目依赖 + 初始化数据库
echo -e "${YELLOW}[10/12] 安装项目依赖并初始化数据库${NC}"
pnpm install
pnpm prisma:push

# 11. 后台启动项目（监听外网 0.0.0.0，生产环境）
echo -e "${YELLOW}[11/12] 启动 TouchGal 项目（生产模式）${NC}"
pkill -f "next dev" || true
pnpm build
nohup pnpm start -- --hostname=0.0.0.0 --port=${PORT} > touchgal-run.log 2>&1 &
sleep 5

# 12. 生成管理员升级脚本 + SSL 自动续期任务
echo -e "${YELLOW}[12/12] 生成管理员工具和 SSL 续期任务${NC}"
# 管理员升级脚本
cat > ${PROJECT_DIR}/make-admin.sh << EOF
#!/bin/bash
read -p "请输入要升级为管理员的用户名：" ADMIN_USER
su - postgres -c "psql -U ${DB_USER} -d ${DB_NAME} -c \"UPDATE \\"User\\" SET \\"isAdmin\\" = true WHERE \\"username\\" = '\\\${ADMIN_USER}';\""
echo "操作完成！若提示 UPDATE 1 则升级成功，若提示 UPDATE 0 则用户名不存在"
EOF
chmod +x ${PROJECT_DIR}/make-admin.sh

# SSL 证书自动续期（Let's Encrypt 证书 90 天有效期）
echo "0 0 1 */2 * root certbot renew --nginx --quiet" >> /etc/crontab
systemctl restart crond

# 部署完成信息
SERVER_IP=$(curl -s ifconfig.me)
echo -e "\n${GREEN}===== TouchGal 部署全部完成！（含 HTTPS 配置）=====${NC}"
echo -e "✅  网站 HTTPS 访问地址：https://${DOMAIN}"
echo -e "✅  备用访问地址：http://${SERVER_IP}:${PORT}（自动跳转 HTTPS）"
echo -e "✅  项目目录：${PROJECT_DIR}"
echo -e "✅  日志文件：${PROJECT_DIR}/touchgal-run.log"
echo -e "\n${YELLOW}📌 管理员升级方法：${NC}"
echo -e "1. 先访问 https://${DOMAIN} 注册账号"
echo -e "2. 执行命令：cd ${PROJECT_DIR} && ./make-admin.sh"
echo -e "\n${YELLOW}⚠️  注意：${NC}"
echo -e "1. 云服务器需放行 80/443/${PORT} 端口"
echo -e "2. SSL 证书已配置自动续期，无需手动管理"
echo -e "3. 查看日志：tail -f ${PROJECT_DIR}/touchgal-run.log"
