#!/bin/bash
# SSL证书安装脚本 - 使用 Let's Encrypt
# 运行前请确保DNS解析已配置完成

set -e

echo "🔐 Life-OS SSL证书安装脚本"
echo "================================"
echo ""

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

# 域名配置
DOMAIN="zhshihe.cn"
EMAIL="admin@zhshihe.cn"  # 请修改为你的邮箱

echo -e "${YELLOW}📝 配置信息:${NC}"
echo "   域名: $DOMAIN"
echo "   邮箱: $EMAIL"
echo ""

# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then 
    echo -e "${RED}❌ 请使用root权限运行此脚本${NC}"
    echo "   sudo bash deploy/setup-ssl.sh"
    exit 1
fi

# 1. 安装Nginx
echo -e "${YELLOW}1️⃣  检查并安装Nginx...${NC}"
if ! command -v nginx &> /dev/null; then
    echo "   安装Nginx..."
    apt update
    apt install -y nginx
    systemctl enable nginx
else
    echo -e "   ${GREEN}✅ Nginx已安装${NC}"
fi

# 2. 安装Certbot
echo -e "\n${YELLOW}2️⃣  检查并安装Certbot...${NC}"
if ! command -v certbot &> /dev/null; then
    echo "   安装Certbot..."
    apt install -y certbot python3-certbot-nginx
else
    echo -e "   ${GREEN}✅ Certbot已安装${NC}"
fi

# 3. 创建certbot验证目录
echo -e "\n${YELLOW}3️⃣  创建证书验证目录...${NC}"
mkdir -p /var/www/certbot
chown -R www-data:www-data /var/www/certbot

# 4. 备份原有Nginx配置
echo -e "\n${YELLOW}4️⃣  备份Nginx配置...${NC}"
if [ -f /etc/nginx/sites-enabled/default ]; then
    mv /etc/nginx/sites-enabled/default /etc/nginx/sites-enabled/default.backup
    echo -e "   ${GREEN}✅ 已备份默认配置${NC}"
fi

# 5. 创建临时配置用于证书申请
echo -e "\n${YELLOW}5️⃣  创建临时Nginx配置...${NC}"
cat > /etc/nginx/sites-available/lifeos-temp << EOF
server {
    listen 80;
    listen [::]:80;
    server_name $DOMAIN www.$DOMAIN;

    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    location / {
        return 200 'SSL setup in progress...';
        add_header Content-Type text/plain;
    }
}
EOF

ln -sf /etc/nginx/sites-available/lifeos-temp /etc/nginx/sites-enabled/lifeos-temp

# 6. 测试并重启Nginx
echo -e "\n${YELLOW}6️⃣  测试Nginx配置...${NC}"
nginx -t
if [ $? -eq 0 ]; then
    systemctl restart nginx
    echo -e "   ${GREEN}✅ Nginx配置正确${NC}"
else
    echo -e "   ${RED}❌ Nginx配置错误${NC}"
    exit 1
fi

# 7. 申请SSL证书
echo -e "\n${YELLOW}7️⃣  申请SSL证书...${NC}"
echo -e "   ${YELLOW}注意: 请确保域名已正确解析到本服务器IP: 119.45.106.76${NC}"
echo -e "   可以运行 'nslookup $DOMAIN' 验证DNS解析"
echo ""
read -p "DNS解析已配置完成？(y/n) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo -e "${RED}❌ 请先配置DNS解析后再运行此脚本${NC}"
    exit 1
fi

certbot certonly \
    --webroot \
    --webroot-path=/var/www/certbot \
    --email $EMAIL \
    --agree-tos \
    --no-eff-email \
    -d $DOMAIN \
    -d www.$DOMAIN

if [ $? -ne 0 ]; then
    echo -e "${RED}❌ SSL证书申请失败${NC}"
    echo -e "${YELLOW}可能的原因:${NC}"
    echo "   1. DNS解析未生效（等待10-60分钟）"
    echo "   2. 防火墙未开放80端口"
    echo "   3. 邮箱格式错误"
    exit 1
fi

echo -e "${GREEN}✅ SSL证书申请成功${NC}"

# 8. 部署正式Nginx配置
echo -e "\n${YELLOW}8️⃣  部署正式Nginx配置...${NC}"
rm -f /etc/nginx/sites-enabled/lifeos-temp
cp /data/MBTI/deploy/nginx.conf /etc/nginx/sites-available/lifeos
ln -sf /etc/nginx/sites-available/lifeos /etc/nginx/sites-enabled/lifeos

# 9. 测试并重启Nginx
echo -e "\n${YELLOW}9️⃣  重启Nginx服务...${NC}"
nginx -t
if [ $? -eq 0 ]; then
    systemctl restart nginx
    echo -e "   ${GREEN}✅ Nginx已重启${NC}"
else
    echo -e "   ${RED}❌ Nginx配置错误${NC}"
    exit 1
fi

# 10. 设置证书自动续期
echo -e "\n${YELLOW}🔟 配置证书自动续期...${NC}"
(crontab -l 2>/dev/null; echo "0 0 1 * * certbot renew --quiet && systemctl reload nginx") | crontab -
echo -e "   ${GREEN}✅ 已设置每月1号自动续期${NC}"

# 11. 配置防火墙
echo -e "\n${YELLOW}1️⃣1️⃣  配置防火墙...${NC}"
if command -v ufw &> /dev/null; then
    ufw allow 80/tcp
    ufw allow 443/tcp
    ufw allow 22/tcp
    echo -e "   ${GREEN}✅ 防火墙规则已添加${NC}"
fi

# 完成
echo ""
echo -e "${GREEN}================================${NC}"
echo -e "${GREEN}🎉 SSL证书安装完成！${NC}"
echo -e "${GREEN}================================${NC}"
echo ""
echo -e "${GREEN}✅ 你现在可以通过以下地址访问:${NC}"
echo -e "   📱 前端: ${GREEN}https://$DOMAIN${NC}"
echo -e "   🔌 后端: ${GREEN}https://$DOMAIN/api${NC}"
echo -e "   📚 API文档: ${GREEN}https://$DOMAIN/docs${NC}"
echo ""
echo -e "${YELLOW}📝 重要提示:${NC}"
echo "   1. 证书有效期: 90天"
echo "   2. 已设置自动续期（每月1号执行）"
echo "   3. 手动续期命令: sudo certbot renew"
echo "   4. 查看证书状态: sudo certbot certificates"
echo ""
echo -e "${YELLOW}🔧 下一步操作:${NC}"
echo "   1. 更新后端环境变量 (life-os-backend/.env)"
echo "   2. 更新前端环境变量 (life-os-web/.env.local)"
echo "   3. 配置微信开放平台回调地址: https://$DOMAIN/api/wechat/callback"
echo "   4. 重启服务: python /data/MBTI/stop.py && python /data/MBTI/start.py"
echo ""

