#!/bin/bash
# hzhub-system 启动脚本

cd "$(dirname "$0")"
mkdir -p logs

# JWT 密钥（必须 >= 32 字节，与 gateway/hzhub-ai 保持一致）
export JWT_SECRET="${JWT_SECRET:-Om1fovSeKIA1oLIoHdDPMF-trbqbrPQoDS3H4u1xoRY}"

PID_FILE="logs/system.pid"

if [ -f "$PID_FILE" ]; then
  PID=$(cat "$PID_FILE")
  if kill -0 "$PID" 2>/dev/null; then
    echo "hzhub-system is already running (PID: $PID)"
    exit 0
  fi
fi

echo "Starting hzhub-system..."
nohup mvn spring-boot:run -Dspring-boot.run.profiles=dev > logs/system.log 2>&1 &
echo $! > "$PID_FILE"

TIMEOUT=30
while [ $TIMEOUT -gt 0 ]; do
  if grep -q "HZHub-System系统服务启动成功" logs/system.log 2>/dev/null; then
    echo "hzhub-system started successfully (PID: $!)"
    echo "Access: http://localhost:8083"
    echo "API Docs: http://localhost:8083/system/api-docs"
    exit 0
  fi
  sleep 1
  TIMEOUT=$((TIMEOUT - 1))
done

echo "hzhub-system started (PID: $!), check logs: tail -f logs/system.log"
