#!/bin/bash
set -e

# 标记文件路径（使用系统级目录）
FLAG_DIR="/var/lib/db-init"
FLAG_FILE="$FLAG_DIR/.db_initialized"

# 数据库连接配置
export PGUSER=supabase_admin
export PGPASSWORD=postgres
export PGHOST=127.0.0.1
export PGPORT=5432
export PGDATABASE=postgres

# 提前创建标记目录
mkdir -p "$FLAG_DIR"

# 如果标记已存在，跳过执行
if [ -f "$FLAG_FILE" ]; then
  echo "✅ Database has already been initialized, skipping."
  exit 0
fi

echo "🚀 Starting database initialization..."

# 执行 migrations
echo "📂 Running migrations..."
for file in $(ls /supabase/chatdesk/supabase/migrations/*.sql | sort); do
  echo "   ▶ Executing $file"
  psql -f "$file"
done

# 执行 seed.sql
echo "🌱 Running seed.sql..."
psql -f /supabase/chatdesk/supabase/seed.sql

# 写入初始化标记
touch "$FLAG_FILE"
echo "✅ Database initialization complete. Marked as initialized at $FLAG_FILE"
