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

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

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/siyuan/deploy.sh  (当前脚本)" >&2
    exit 1
fi
source "$BASE_DIR/setup.sh"

# =============================================================
#  SiYuan 专用函数
# =============================================================

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

    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 "│  SIYUAN_DOMAIN=note.yourdomain.com              │"
        warn "│  CERTBOT_EMAIL=you@yourdomain.com               │"
        warn "│  SIYUAN_ACCESS_CODE=你的访问授权码                │"
        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 "${SIYUAN_DOMAIN:-}" ]] || [[ "${SIYUAN_DOMAIN}" == "note.example.com" ]]; then
        error "请在 .env 中将 SIYUAN_DOMAIN 修改为你的实际域名"
        has_error=1
    fi
    if [[ -z "${CERTBOT_EMAIL:-}" ]] || [[ "${CERTBOT_EMAIL}" == "admin@example.com" ]]; then
        error "请在 .env 中将 CERTBOT_EMAIL 修改为你的实际邮箱"
        has_error=1
    fi
    if [[ -z "${SIYUAN_ACCESS_CODE:-}" ]] || [[ "${SIYUAN_ACCESS_CODE}" == "changeme" ]]; then
        error "请在 .env 中将 SIYUAN_ACCESS_CODE 修改为一个安全的授权码"
        has_error=1
    fi
    [ "$has_error" -eq 1 ] && { error "请修改 .env 后重新运行"; exit 1; }

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

create_dirs() {
    step "创建数据目录"
    local data_dir="${SIYUAN_DATA_DIR:-/data/siyuan/workspace}"
    local backup_dir="${BACKUP_DIR:-/var/backups/siyuan}"
    local puid="${SIYUAN_PUID:-1000}"
    local pgid="${SIYUAN_PGID:-1000}"

    mkdir -p "$data_dir" "$backup_dir"
    chown -R "$puid:$pgid" "$data_dir"
    log "数据目录: $data_dir (所有者: $puid:$pgid)"
    log "备份目录: $backup_dir"
}

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

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

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

    log "等待 SiYuan 就绪..."
    local max_wait=30
    for i in $(seq 1 "$max_wait"); do
        if curl -sf http://127.0.0.1:6806/ &> /dev/null; then
            log "SiYuan 启动成功！"
            return
        fi
        sleep 2
    done
    warn "SiYuan 可能仍在启动中，请稍后检查: docker compose logs -f"
}

show_info() {
    set -a; source .env; set +a

    echo ""
    echo -e "${GREEN}╔══════════════════════════════════════════════════════════╗${NC}"
    echo -e "${GREEN}║              SiYuan 笔记部署完成！                       ║${NC}"
    echo -e "${GREEN}╠══════════════════════════════════════════════════════════╣${NC}"
    echo -e "${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}  Web 访问:  ${CYAN}https://${SIYUAN_DOMAIN}${NC}"
    echo -e "${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}  访问授权码: 在 .env 中的 SIYUAN_ACCESS_CODE"
    echo -e "${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}  数据目录:  ${SIYUAN_DATA_DIR:-/data/siyuan/workspace}"
    echo -e "${GREEN}║${NC}  备份目录:  ${BACKUP_DIR:-/var/backups/siyuan}"
    echo -e "${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}  ${YELLOW}⚠ Docker 版不支持桌面/移动客户端连接${NC}"
    echo -e "${GREEN}║${NC}  ${YELLOW}⚠ 不支持导出 PDF/Word/HTML 和导入 Markdown${NC}"
    echo -e "${GREEN}║${NC}"
    echo -e "${GREEN}╚══════════════════════════════════════════════════════════╝${NC}"
    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 "  备份数据:    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: 配置防火墙
    setup_firewall_base

    # Step 8: 配置 SSL 证书
    setup_ssl_cert "${SIYUAN_DOMAIN}" "${CERTBOT_EMAIL}" "siyuan"

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

    # Step 10: 启动服务
    start_services

    # 完成
    show_info
}

main "$@"
