#!/bin/bash

# urban-lifeline Docker Compose 启动脚本

set -e

# If the user invoked this script with `sh start.sh` (which may be dash),
# some Bash-specific features (like ${BASH_SOURCE[0]} and [[ .. ]]) will
# fail with "Bad substitution". If we're not running under Bash, try to
# re-exec the script using `bash` if available.
if [ -z "$BASH_VERSION" ]; then
    if command -v bash >/dev/null 2>&1; then
        echo "脚本需要 Bash，正在重新以 Bash 执行..."
        exec bash "$0" "$@"
    else
        echo "错误: 需要 Bash 运行此脚本，但系统未安装 Bash。"
        exit 1
    fi
fi
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
DATA_DIR="$PROJECT_ROOT/.data/docker"

echo "=========================================="
echo "urban-lifeline Docker 开发环境启动"
echo "=========================================="
echo "项目目录: $PROJECT_ROOT"
echo "数据目录: $DATA_DIR"
echo ""

# 1. 检查 Docker
echo "1. 检查 Docker..."
if ! command -v docker &> /dev/null; then
    echo "❌ 错误: 未找到 Docker"
    echo "请先安装 Docker: https://docs.docker.com/get-docker/"
    exit 1
fi

if ! docker info &> /dev/null; then
    echo "❌ 错误: Docker 未运行"
    echo "请启动 Docker 服务"
    exit 1
fi
echo "✓ Docker 检查完成"
echo ""

# 2. 检查 Docker Compose
echo "2. 检查 Docker Compose..."
if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then
    echo "❌ 错误: 未找到 Docker Compose"
    echo "请先安装 Docker Compose: https://docs.docker.com/compose/install/"
    exit 1
fi
echo "✓ Docker Compose 检查完成"
echo ""

# 3. 检查主机 MySQL
echo "3. 检查主机 MySQL..."
if command -v mysql &> /dev/null; then
    echo "请输入 MySQL 连接信息 (按 Enter 使用默认值):"
    read -p "  主机 [127.0.0.1]: " MYSQL_HOST
    MYSQL_HOST=${MYSQL_HOST:-127.0.0.1}
    
    read -p "  端口 [3306]: " MYSQL_PORT
    MYSQL_PORT=${MYSQL_PORT:-3306}
    
    read -p "  用户名 [root]: " MYSQL_USER
    MYSQL_USER=${MYSQL_USER:-root}
    
    read -s -p "  密码 [123456]: " MYSQL_PASSWORD
    echo
    MYSQL_PASSWORD=${MYSQL_PASSWORD:-123456}
    
    read -p "  数据库名 [nacos_config]: " MYSQL_DB
    MYSQL_DB=${MYSQL_DB:-nacos_config}
    
    echo ""
    echo "测试 MySQL 连接..."
    if mysql -h"$MYSQL_HOST" -P"$MYSQL_PORT" -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" -e "USE $MYSQL_DB;" 2>/dev/null; then
        echo "✓ MySQL 连接成功"
    else
        echo "⚠️  警告: MySQL 连接失败"
        echo ""
        echo "请确保:"
        echo "  1. MySQL 服务正在运行"
        echo "  2. 数据库 '$MYSQL_DB' 已创建"
        echo "  3. 用户 '$MYSQL_USER' 有权限访问该数据库"
        echo ""
        read -p "是否继续启动? (y/N): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            exit 1
        fi
    fi
else
    echo "⚠️  警告: 未找到 mysql 客户端，无法验证数据库连接"
    echo "将使用默认配置: root:123456@localhost:3306/nacos_config"
    MYSQL_USER=root
    MYSQL_PASSWORD=123456
    MYSQL_DB=nacos_config
fi
echo ""

# 4. 创建数据目录
echo "4. 创建数据目录..."
mkdir -p "$DATA_DIR"/nacos/{data,logs}
echo "✓ 数据目录创建完成"
echo ""

# 5. 更新 docker-compose.yml 配置
if [ -n "$MYSQL_USER" ] && [ "$MYSQL_USER" != "root" ]; then
    echo "5. 更新 Docker Compose 配置..."
    
    # 创建临时 .env 文件
    cat > "$SCRIPT_DIR/.env" <<EOF
MYSQL_SERVICE_USER=$MYSQL_USER
MYSQL_SERVICE_PASSWORD=$MYSQL_PASSWORD
MYSQL_SERVICE_DB_NAME=$MYSQL_DB
EOF
    
    echo "✓ 配置更新完成"
    echo ""
fi

# 6. 拉取镜像
echo "6. 拉取 Nacos 镜像..."
cd "$SCRIPT_DIR"
if command -v docker-compose &> /dev/null; then
    docker-compose pull
else
    docker compose pull
fi
echo "✓ 镜像拉取完成"
echo ""

# 7. 启动服务
echo "7. 启动服务..."
if command -v docker-compose &> /dev/null; then
    docker-compose up -d
else
    docker compose up -d
fi
echo "✓ 服务启动完成"
echo ""

# 8. 等待 Nacos 启动
echo "8. 等待 Nacos 启动..."
echo "   这可能需要 30-60 秒..."

MAX_WAIT=60
WAITED=0
while [ $WAITED -lt $MAX_WAIT ]; do
    if curl -s http://localhost:8848/nacos/ > /dev/null 2>&1; then
        echo "✓ Nacos 启动成功"
        break
    fi
    sleep 2
    WAITED=$((WAITED + 2))
    echo -n "."
done
echo ""

if [ $WAITED -ge $MAX_WAIT ]; then
    echo "⚠️  警告: Nacos 启动超时"
    echo ""
    echo "查看日志:"
    if command -v docker-compose &> /dev/null; then
        docker-compose logs nacos
    else
        docker compose logs nacos
    fi
    echo ""
    echo "请检查 MySQL 连接配置是否正确"
    exit 1
fi

# 9. 显示服务信息
echo ""
echo "=========================================="
echo "✅ urban-lifeline 开发环境启动完成！"
echo "=========================================="
echo ""
echo "服务访问地址："
echo "  - Nacos 控制台: http://localhost:8848/nacos/"
echo "  - Nacos 默认账号: nacos / nacos"
echo ""
echo "数据库连接信息："
echo "  - 数据库: ${MYSQL_DB:-nacos_config}"
echo "  - 用户: ${MYSQL_USER:-root}"
echo ""
echo "数据持久化目录："
echo "  - $DATA_DIR/nacos/data"
echo "  - $DATA_DIR/nacos/logs"
echo ""
echo "常用命令："
echo "  查看运行状态:"
echo "    docker ps"
echo ""
echo "  查看 Nacos 日志:"
echo "    docker logs -f urban-lifeline-nacos"
echo ""
echo "  停止服务:"
echo "    cd $SCRIPT_DIR && docker-compose down"
echo ""
echo "  重启服务:"
echo "    cd $SCRIPT_DIR && docker-compose restart"
echo ""
echo "  完全清理（删除容器和网络）:"
echo "    cd $SCRIPT_DIR && docker-compose down -v"
echo ""
