#!/bin/bash
# =============================================================================
# MPC gRPC 代理 - Nginx 配置安装脚本
# =============================================================================
# 用途: 为 Service Party App 提供 gRPC 连接到 Message Router
# 域名: mpc-grpc.szaiai.com
#
# 前提条件:
#   1. Nginx 已安装并运行
#   2. Certbot 已安装
#   3. DNS 已配置 mpc-grpc.szaiai.com 指向此服务器
#   4. Message Router 在后端服务器 (192.168.1.111:50051) 运行
#
# 此脚本完全独立，不影响现有服务
# =============================================================================

set -e

DOMAIN="mpc-grpc.szaiai.com"
DOMAIN_CONF="${DOMAIN}.conf"  # Nginx 配置文件需要 .conf 后缀
EMAIL="admin@szaiai.com"
BACKEND_HOST="192.168.1.111"
BACKEND_PORT="50051"

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

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# 检查 root 权限
check_root() {
    if [ "$EUID" -ne 0 ]; then
        log_error "请使用 root 权限运行: sudo ./install-mpc-grpc.sh"
        exit 1
    fi
}

# 检查前提条件
check_prerequisites() {
    log_info "检查前提条件..."

    # 检查 Nginx
    if ! command -v nginx &> /dev/null; then
        log_error "Nginx 未安装，请先安装 Nginx"
        exit 1
    fi

    # 检查 Certbot
    if ! command -v certbot &> /dev/null; then
        log_error "Certbot 未安装，请先安装 Certbot"
        exit 1
    fi

    # 检查 Nginx 是否支持 http2 和 grpc
    if ! nginx -V 2>&1 | grep -q "http_v2_module"; then
        log_warn "Nginx 可能不支持 HTTP/2，gRPC 需要 HTTP/2 支持"
    fi

    log_success "前提条件检查通过"
}

# 步骤 1: 创建临时 HTTP 配置用于证书申请
configure_http() {
    log_info "步骤 1/4: 创建临时 HTTP 配置..."

    # 确保 certbot webroot 目录及子目录存在
    mkdir -p /var/www/certbot/.well-known/acme-challenge
    chmod -R 755 /var/www/certbot

    # 创建临时 HTTP 配置 (使用 .conf 后缀以便 nginx 加载)
    cat > /etc/nginx/sites-available/$DOMAIN_CONF << EOF
# 临时 HTTP 配置 - 用于 Let's Encrypt 验证
server {
    listen 80;
    listen [::]:80;
    server_name $DOMAIN;

    # Let's Encrypt 验证目录
    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    location / {
        return 200 'MPC gRPC proxy - waiting for SSL certificate';
        add_header Content-Type text/plain;
    }
}
EOF

    # 启用站点
    ln -sf /etc/nginx/sites-available/$DOMAIN_CONF /etc/nginx/sites-enabled/$DOMAIN_CONF

    # 测试并重载
    nginx -t && systemctl reload nginx
    log_success "临时 HTTP 配置完成"
}

# 步骤 2: 申请 SSL 证书
obtain_certificate() {
    log_info "步骤 2/4: 申请 Let's Encrypt SSL 证书..."

    # 检查证书是否已存在
    if [ -f "/etc/letsencrypt/live/$DOMAIN/fullchain.pem" ]; then
        log_warn "证书已存在，跳过申请"
        return 0
    fi

    # 申请证书
    certbot certonly \
        --webroot \
        --webroot-path=/var/www/certbot \
        --email $EMAIL \
        --agree-tos \
        --no-eff-email \
        -d $DOMAIN

    log_success "SSL 证书申请成功"
}

# 步骤 3: 配置 gRPC 代理
configure_grpc() {
    log_info "步骤 3/4: 配置 Nginx gRPC 代理..."

    # 获取脚本所在目录
    SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

    # 复制 gRPC 配置
    cp "$SCRIPT_DIR/mpc-grpc.szaiai.com.conf" /etc/nginx/sites-available/$DOMAIN_CONF

    # 测试并重载
    nginx -t && systemctl reload nginx
    log_success "gRPC 代理配置完成"
}

# 步骤 4: 验证配置
verify_setup() {
    log_info "步骤 4/4: 验证配置..."

    # 检查 Nginx 状态
    if systemctl is-active --quiet nginx; then
        log_success "Nginx 运行正常"
    else
        log_error "Nginx 未运行"
        exit 1
    fi

    # 检查证书
    if [ -f "/etc/letsencrypt/live/$DOMAIN/fullchain.pem" ]; then
        log_success "SSL 证书已就绪"
    else
        log_error "SSL 证书未找到"
        exit 1
    fi

    # 检查配置语法
    if nginx -t 2>/dev/null; then
        log_success "Nginx 配置语法正确"
    else
        log_error "Nginx 配置语法错误"
        exit 1
    fi

    log_success "验证完成"
}

# 显示完成信息
show_completion() {
    echo ""
    echo -e "${GREEN}========================================${NC}"
    echo -e "${GREEN}   MPC gRPC 代理安装完成!${NC}"
    echo -e "${GREEN}========================================${NC}"
    echo ""
    echo -e "gRPC 端点: ${BLUE}mpc-grpc.szaiai.com:443${NC}"
    echo ""
    echo "架构:"
    echo "  Service Party App → Nginx (SSL/gRPC) → Message Router"
    echo "                          ↓"
    echo "                   $DOMAIN:443"
    echo "                          ↓"
    echo "                   $BACKEND_HOST:$BACKEND_PORT"
    echo ""
    echo "Service Party App 连接配置:"
    echo "  gRPC 地址: mpc-grpc.szaiai.com:443"
    echo "  TLS: 启用"
    echo ""
    echo "常用命令:"
    echo "  查看 Nginx 状态:  systemctl status nginx"
    echo "  重载 Nginx:       systemctl reload nginx"
    echo "  查看证书:         certbot certificates"
    echo "  查看日志:         tail -f /var/log/nginx/$DOMAIN.access.log"
    echo ""
    echo -e "${YELLOW}注意: 确保后端 Message Router ($BACKEND_HOST:$BACKEND_PORT) 正在运行${NC}"
    echo ""
}

# 显示使用帮助
show_help() {
    echo "用法: $0 [选项]"
    echo ""
    echo "选项:"
    echo "  --help, -h     显示帮助信息"
    echo "  --verify       仅验证现有配置"
    echo "  --uninstall    卸载配置"
    echo ""
}

# 卸载配置
uninstall() {
    log_info "卸载 MPC gRPC 代理配置..."

    # 移除站点配置 (兼容新旧文件名)
    rm -f /etc/nginx/sites-enabled/$DOMAIN_CONF
    rm -f /etc/nginx/sites-available/$DOMAIN_CONF
    rm -f /etc/nginx/sites-enabled/$DOMAIN
    rm -f /etc/nginx/sites-available/$DOMAIN

    # 重载 Nginx
    nginx -t && systemctl reload nginx

    log_success "配置已卸载"
    log_info "注意: SSL 证书未删除，如需删除请运行: certbot delete --cert-name $DOMAIN"
}

# 主函数
main() {
    case "${1:-}" in
        --help|-h)
            show_help
            exit 0
            ;;
        --verify)
            check_prerequisites
            verify_setup
            exit 0
            ;;
        --uninstall)
            check_root
            uninstall
            exit 0
            ;;
    esac

    echo ""
    echo "============================================"
    echo "  MPC gRPC 代理 - Nginx 安装脚本"
    echo "  域名: $DOMAIN"
    echo "  后端: $BACKEND_HOST:$BACKEND_PORT"
    echo "============================================"
    echo ""

    check_root
    check_prerequisites

    echo ""
    log_warn "请确保以下条件已满足:"
    echo "  1. 域名 $DOMAIN 的 DNS A 记录已指向本服务器 IP"
    echo "  2. Message Router 已在 $BACKEND_HOST:$BACKEND_PORT 运行"
    echo ""
    read -p "是否继续安装? (y/n): " confirm

    if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
        log_info "安装已取消"
        exit 0
    fi

    configure_http
    obtain_certificate
    configure_grpc
    verify_setup
    show_completion
}

main "$@"
