#!/usr/bin/env bash
set -euo pipefail

# ============================================
# RustDesk Server 一键部署脚本
# 自动安装 Docker + Nginx + SSL + RustDesk
# ============================================

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

# ===== 加载公共基础函数 =====
BASE_DIR="$(cd "$SCRIPT_DIR/../base" 2>/dev/null && pwd)" || true
if [ -z "$BASE_DIR" ] || [ ! -f "$BASE_DIR/setup.sh" ]; then
    echo "[ERROR] base/setup.sh 未找到" >&2
    echo "请确保目录结构如下:" >&2
    echo "  /opt/base/setup.sh" >&2
    echo "  /opt/rustdesk/deploy.sh  (当前脚本)" >&2
    exit 1
fi
source "$BASE_DIR/setup.sh"

# =============================================================
#  RustDesk 专用函数
# =============================================================

init_env() {
    step "初始化 RustDesk 配置"

    if [ ! -f .env ]; then
        if [ ! -f .env.example ]; then
            error "缺少 .env.example 模板文件"
            exit 1
        fi
        cp .env.example .env
        log "已生成 .env 文件"
        echo ""
        warn "┌─────────────────────────────────────────────────┐"
        warn "│  请编辑 .env 文件，至少修改以下配置：              │"
        warn "│                                                 │"
        warn "│  RUSTDESK_DOMAIN=rustdesk.yourdomain.com        │"
        warn "│  CERTBOT_EMAIL=you@yourdomain.com               │"
        warn "│                                                 │"
        warn "│  编辑命令: vi $SCRIPT_DIR/.env                  │"
        warn "│  编辑完成后重新运行: bash deploy.sh              │"
        warn "└─────────────────────────────────────────────────┘"
        exit 0
    fi

    fix_crlf .env
    set -a; source .env; set +a

    local has_error=0
    if [[ -z "${RUSTDESK_DOMAIN:-}" ]] || [[ "${RUSTDESK_DOMAIN}" == "rustdesk.example.com" ]]; then
        error "请在 .env 中将 RUSTDESK_DOMAIN 修改为你的实际域名"
        has_error=1
    fi
    if [[ -z "${CERTBOT_EMAIL:-}" ]] || [[ "${CERTBOT_EMAIL}" == "admin@example.com" ]]; then
        error "请在 .env 中将 CERTBOT_EMAIL 修改为你的实际邮箱"
        has_error=1
    fi
    [ "$has_error" -eq 1 ] && { error "请修改 .env 后重新运行"; exit 1; }

    log "配置检查通过"
    log "  域名: ${RUSTDESK_DOMAIN}"
    log "  邮箱: ${CERTBOT_EMAIL}"
}

create_dirs() {
    step "创建数据目录"
    local data_dir="${RUSTDESK_DATA_DIR:-/var/lib/rustdesk}"
    local backup_dir="${BACKUP_DIR:-/var/backups/rustdesk}"

    mkdir -p "$data_dir" "$backup_dir"
    log "数据目录: $data_dir"
    log "备份目录: $backup_dir"
}

setup_firewall_rustdesk() {
    step "配置 RustDesk 防火墙规则"

    if command -v ufw &>/dev/null; then
        ufw allow 21115/tcp comment "RustDesk NAT type test"
        ufw allow 21116/tcp comment "RustDesk TCP hole punching"
        ufw allow 21116/udp comment "RustDesk ID registration/heartbeat"
        ufw allow 21117/tcp comment "RustDesk Relay"
        log "已添加 UFW 规则 (21115-21117)"
    elif command -v firewall-cmd &>/dev/null; then
        firewall-cmd --permanent --add-port=21115/tcp
        firewall-cmd --permanent --add-port=21116/tcp
        firewall-cmd --permanent --add-port=21116/udp
        firewall-cmd --permanent --add-port=21117/tcp
        firewall-cmd --reload
        log "已添加 firewalld 规则 (21115-21117)"
    else
        warn "未检测到防火墙管理工具，请手动放行端口 21115-21117"
    fi
}

start_services() {
    step "启动 RustDesk 服务"

    log "正在拉取镜像..."
    docker compose pull

    log "正在启动容器..."
    docker compose up -d

    log "等待 RustDesk 就绪..."
    sleep 5

    # 检查容器是否正常运行
    if docker compose ps | grep -q "running"; then
        log "RustDesk 服务启动成功！"
    else
        warn "RustDesk 可能仍在启动中，请稍后检查: docker compose logs -f"
    fi
}

show_public_key() {
    step "获取公钥信息"
    local data_dir="${RUSTDESK_DATA_DIR:-/var/lib/rustdesk}"
    local key_file="$data_dir/id_ed25519.pub"

    if [ -f "$key_file" ]; then
        local pub_key
        pub_key=$(cat "$key_file")
        echo ""
        echo -e "${CYAN}══════════════════════════════════════════════════════════${NC}"
        echo -e "${CYAN}  RustDesk 公钥（客户端配置时需要）：${NC}"
        echo -e "${CYAN}══════════════════════════════════════════════════════════${NC}"
        echo ""
        echo -e "  ${GREEN}${pub_key}${NC}"
        echo ""
        echo -e "${CYAN}══════════════════════════════════════════════════════════${NC}"
        echo ""
    else
        warn "公钥文件尚未生成，服务启动后会自动创建"
        warn "稍后可查看: cat $key_file"
    fi
}

show_info() {
    set -a; source .env; set +a
    local server_ip
    server_ip=$(curl -sf https://api.ipify.org 2>/dev/null || curl -sf https://ifconfig.me 2>/dev/null || echo "<服务器IP>")

    echo ""
    echo -e "${GREEN}╔══════════════════════════════════════════════════════════╗${NC}"
    echo -e "${GREEN}║             RustDesk Server 部署完成！                   ║${NC}"
    echo -e "${GREEN}╠══════════════════════════════════════════════════════════╣${NC}"
    echo -e "${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}  服务器 IP:   ${CYAN}${server_ip}${NC}"
    echo -e "${GREEN}║${NC}  域名:        ${CYAN}${RUSTDESK_DOMAIN}${NC}"
    echo -e "${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}  hbbs 端口:   21115/tcp, 21116/tcp+udp"
    echo -e "${GREEN}║${NC}  hbbr 端口:   21117/tcp"
    echo -e "${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}  数据目录:    ${RUSTDESK_DATA_DIR:-/var/lib/rustdesk}"
    echo -e "${GREEN}║${NC}  备份目录:    ${BACKUP_DIR:-/var/backups/rustdesk}"
    echo -e "${GREEN}║${NC}"
    echo -e "${GREEN}╚══════════════════════════════════════════════════════════╝${NC}"
    echo ""

    show_public_key

    echo "客户端配置："
    echo "  ID 服务器:   ${RUSTDESK_DOMAIN}"
    echo "  中继服务器:  ${RUSTDESK_DOMAIN}"
    echo "  Key:         (上方公钥)"
    echo ""
    echo "常用命令:"
    echo "  查看日志:    cd $SCRIPT_DIR && docker compose logs -f"
    echo "  重启服务:    cd $SCRIPT_DIR && docker compose restart"
    echo "  停止服务:    cd $SCRIPT_DIR && docker compose down"
    echo "  查看公钥:    cat ${RUSTDESK_DATA_DIR:-/var/lib/rustdesk}/id_ed25519.pub"
    echo "  备份数据:    cd $SCRIPT_DIR && bash backup.sh"
    echo ""
}

# =============================================================
#  主流程
# =============================================================
main() {
    echo -e "${CYAN}"
    echo "  ____            _   ____            _    "
    echo " |  _ \\ _   _ ___| |_|  _ \\  ___  ___| | __"
    echo " | |_) | | | / __| __| | | |/ _ \\/ __| |/ /"
    echo " |  _ <| |_| \\__ \\ |_| |_| |  __/\\__ \\   < "
    echo " |_| \\_\\\\__,_|___/\\__|____/ \\___||___/_|\\_\\  Deploy Script"
    echo -e "${NC}"
    echo ""

    check_root
    load_base_env "$BASE_DIR"

    # Step 1: 系统初始化
    init_system

    # Step 2: 安装 Docker
    install_docker

    # Step 3: 安装 Nginx
    install_nginx

    # Step 4: 初始化配置
    init_env

    # Step 5: 配置 Docker 镜像加速
    configure_docker_mirrors

    # Step 6: 创建数据目录
    create_dirs

    # Step 7: 配置防火墙（基础 + RustDesk 端口）
    setup_firewall_base
    setup_firewall_rustdesk

    # Step 8: 配置 SSL 证书
    setup_ssl_cert "${RUSTDESK_DOMAIN}" "${CERTBOT_EMAIL}" "rustdesk"

    # Step 9: 部署 Nginx 反向代理
    deploy_nginx_conf "$SCRIPT_DIR/nginx/rustdesk.conf" "${RUSTDESK_DOMAIN}" "rustdesk"

    # Step 10: 启动服务
    start_services

    # 显示部署信息
    show_info
    log "===== RustDesk Server 部署完成 ====="
}

main "$@"
