#!/bin/bash

# 启动数据库容器脚本
# 作者: 张翔
# 日期: 2026-04-15

set -e

echo "=========================================="
echo "启动 PostgreSQL 数据库容器"
echo "=========================================="

# 检查Docker是否运行
if ! docker info > /dev/null 2>&1; then
    echo "错误: Docker 未运行，请启动Docker服务"
    exit 1
fi

# 检查docker-compose是否可用
if ! command -v docker-compose &> /dev/null; then
    echo "错误: docker-compose 未安装"
    exit 1
fi

# 进入项目根目录
cd "$(dirname "$0")/.."

echo "1. 停止已运行的容器..."
docker-compose down postgres 2>/dev/null || true

echo "2. 启动 PostgreSQL 容器..."
docker-compose up -d postgres

echo "3. 等待数据库就绪..."
for i in {1..30}; do
    if docker-compose exec postgres pg_isready -U novalon -d manage_system > /dev/null 2>&1; then
        echo "数据库已就绪！"
        break
    fi
    echo "等待数据库启动... ($i/30)"
    sleep 2
done

# 最终检查
if docker-compose exec postgres pg_isready -U novalon -d manage_system > /dev/null 2>&1; then
    echo "=========================================="
    echo "✅ 数据库启动成功！"
    echo "连接信息:"
    echo "  - 主机: localhost"
    echo "  - 端口: 55432"
    echo "  - 数据库: manage_system"
    echo "  - 用户名: novalon"
    echo "  - 密码: novalon123"
    echo "=========================================="
    
    # 显示容器状态
    echo "容器状态:"
    docker-compose ps postgres
    
    # 显示日志最后几行
    echo -e "\n数据库日志:"
    docker-compose logs --tail=10 postgres
else
    echo "=========================================="
    echo "❌ 数据库启动失败"
    echo "请检查错误日志:"
    docker-compose logs postgres
    echo "=========================================="
    exit 1
fi