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

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

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

# =============================================================
#  Portainer 专用函数
# =============================================================

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

    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 "│  PORTAINER_DOMAIN=docker.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 "${PORTAINER_DOMAIN:-}" ]] || [[ "${PORTAINER_DOMAIN}" == "docker.example.com" ]]; then
        error "请在 .env 中将 PORTAINER_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 "  域名: ${PORTAINER_DOMAIN}"
    log "  邮箱: ${CERTBOT_EMAIL}"
}

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

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

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

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

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

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

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

    echo ""
    echo -e "${GREEN}╔══════════════════════════════════════════════════════════╗${NC}"
    echo -e "${GREEN}║             Portainer CE 部署完成！                      ║${NC}"
    echo -e "${GREEN}╠══════════════════════════════════════════════════════════╣${NC}"
    echo -e "${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}  Web 访问:  ${CYAN}https://${PORTAINER_DOMAIN}${NC}"
    echo -e "${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}  数据目录:  ${PORTAINER_DATA_DIR:-/var/lib/portainer}"
    echo -e "${GREEN}║${NC}  备份目录:  ${BACKUP_DIR:-/var/backups/portainer}"
    echo -e "${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}  ${RED}⚠ 首次访问请在 5 分钟内创建管理员账号！${NC}"
    echo -e "${GREEN}║${NC}  ${RED}⚠ 超时未创建将需要重启容器。${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 "${PORTAINER_DOMAIN}" "${CERTBOT_EMAIL}" "portainer"

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

    # Step 10: 启动服务
    start_services

    # 显示部署信息
    show_info
    log "===== Portainer CE 部署完成 ====="
}

main "$@"
