#!/bin/bash
# =============================================================================
# Sentry Self-Hosted 部署脚本
# =============================================================================
# 使用方法:
#   ./deploy.sh init      # 首次初始化 (创建管理员账号)
#   ./deploy.sh up        # 启动服务
#   ./deploy.sh down      # 停止服务
#   ./deploy.sh logs      # 查看日志
#   ./deploy.sh status    # 查看状态
#   ./deploy.sh upgrade   # 升级 Sentry
# =============================================================================

set -e

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

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

# 检查 .env 文件
check_env() {
    if [ ! -f .env ]; then
        echo -e "${YELLOW}未找到 .env 文件，正在从模板创建...${NC}"
        cp .env.example .env

        # 生成随机密钥
        RANDOM_KEY=$(openssl rand -hex 32 2>/dev/null || head -c 64 /dev/urandom | base64 | tr -d '\n' | head -c 64)
        sed -i "s/please_change_this_to_a_random_string_at_least_50_chars/$RANDOM_KEY/" .env

        echo -e "${GREEN}.env 文件已创建，请检查并修改配置后重新运行${NC}"
        echo -e "${YELLOW}特别注意修改: SENTRY_SECRET_KEY 和 SENTRY_DB_PASSWORD${NC}"
    fi
}

# 初始化 Sentry (首次运行)
init() {
    echo -e "${GREEN}=== 初始化 Sentry ===${NC}"
    check_env

    echo -e "${YELLOW}1. 启动依赖服务...${NC}"
    docker compose up -d sentry-redis sentry-postgres sentry-kafka sentry-zookeeper sentry-clickhouse

    echo -e "${YELLOW}等待服务就绪...${NC}"
    sleep 30

    echo -e "${YELLOW}2. 运行数据库迁移...${NC}"
    docker compose run --rm sentry-web upgrade --noinput

    echo -e "${YELLOW}3. 创建管理员账号...${NC}"
    echo -e "${GREEN}请按提示输入管理员邮箱和密码${NC}"
    docker compose run --rm sentry-web createuser --superuser

    echo -e "${GREEN}=== 初始化完成 ===${NC}"
    echo -e "${YELLOW}运行 './deploy.sh up' 启动所有服务${NC}"
}

# 启动服务
up() {
    echo -e "${GREEN}=== 启动 Sentry ===${NC}"
    check_env
    docker compose up -d
    echo -e "${GREEN}Sentry 已启动${NC}"
    echo -e "Web UI: http://localhost:${SENTRY_PORT:-9000}"
    echo -e "Relay:  http://localhost:${SENTRY_RELAY_PORT:-3000}"
}

# 停止服务
down() {
    echo -e "${YELLOW}=== 停止 Sentry ===${NC}"
    docker compose down
    echo -e "${GREEN}Sentry 已停止${NC}"
}

# 查看日志
logs() {
    SERVICE=${1:-}
    if [ -z "$SERVICE" ]; then
        docker compose logs -f --tail=100
    else
        docker compose logs -f --tail=100 "$SERVICE"
    fi
}

# 查看状态
status() {
    echo -e "${GREEN}=== Sentry 服务状态 ===${NC}"
    docker compose ps
}

# 升级
upgrade() {
    echo -e "${YELLOW}=== 升级 Sentry ===${NC}"

    echo "1. 停止服务..."
    docker compose down

    echo "2. 拉取最新镜像..."
    docker compose pull

    echo "3. 运行数据库迁移..."
    docker compose run --rm sentry-web upgrade --noinput

    echo "4. 启动服务..."
    docker compose up -d

    echo -e "${GREEN}=== 升级完成 ===${NC}"
}

# 生成 Relay 凭证
generate_relay_credentials() {
    echo -e "${YELLOW}=== 生成 Relay 凭证 ===${NC}"
    docker compose run --rm sentry-relay credentials generate --stdout > relay/credentials.json
    echo -e "${GREEN}凭证已生成到 relay/credentials.json${NC}"
}

# 帮助信息
help() {
    echo "Sentry Self-Hosted 部署脚本"
    echo ""
    echo "用法: ./deploy.sh <命令>"
    echo ""
    echo "命令:"
    echo "  init                首次初始化 (创建管理员账号)"
    echo "  up                  启动所有服务"
    echo "  down                停止所有服务"
    echo "  logs [service]      查看日志 (可指定服务)"
    echo "  status              查看服务状态"
    echo "  upgrade             升级 Sentry"
    echo "  generate-relay      生成 Relay 凭证"
    echo "  help                显示此帮助信息"
    echo ""
    echo "示例:"
    echo "  ./deploy.sh init              # 首次安装"
    echo "  ./deploy.sh up                # 启动"
    echo "  ./deploy.sh logs sentry-web   # 查看 Web 服务日志"
}

# 主入口
case "${1:-help}" in
    init)
        init
        ;;
    up)
        up
        ;;
    down)
        down
        ;;
    logs)
        logs "$2"
        ;;
    status)
        status
        ;;
    upgrade)
        upgrade
        ;;
    generate-relay)
        generate_relay_credentials
        ;;
    help|--help|-h)
        help
        ;;
    *)
        echo -e "${RED}未知命令: $1${NC}"
        help
        exit 1
        ;;
esac
