#!/bin/bash
# 啟動 CodiMD 資料庫 Port Forward

DB_SVC="codimd-db"
DB_NAMESPACE="default"
LOCAL_PORT="5432"
REMOTE_PORT="5432"
REMOTE_HOST="ubuntu@192.168.42.120"

echo "=== 啟動 CodiMD 資料庫 Port Forward ==="

# 檢查是否已經在運行
if pgrep -f "port-forward.*${DB_SVC}" > /dev/null; then
    echo "⚠️  Port-forward 已經在運行中"
    echo "   使用 ./db-port-forward-stop.sh 來停止"
    exit 1
fi

# 透過 SSH 執行 kubectl port-forward
ssh -L ${LOCAL_PORT}:localhost:${REMOTE_PORT} ${REMOTE_HOST} \
    "sudo kubectl port-forward -n ${DB_NAMESPACE} svc/${DB_SVC} ${LOCAL_PORT}:${REMOTE_PORT}" \
    &

PF_PID=$!
echo $PF_PID > /tmp/codimd-db-port-forward.pid

# 等待 port 開始監聽
echo "⏳ 等待 port-forward 建立..."
for i in {1..10}; do
    if nc -z localhost ${LOCAL_PORT} 2>/dev/null; then
        echo "✅ Port-forward 已建立: localhost:${LOCAL_PORT} -> ${DB_SVC}:${REMOTE_PORT}"
        echo "   PID: $PF_PID"
        echo ""
        echo "現在可以使用 cli-anything-codimd:"
        echo ""
        echo "   cli-anything-codimd admin list-users \\"
        echo "     --db-type postgresql \\"
        echo "     --db-host localhost \\"
        echo "     --db-name codimd \\"
        echo "     --db-user codimd \\"
        echo "     --db-password 8xG94tL0uKlGiBEd"
        echo ""
        echo "停止方式: ./db-port-forward-stop.sh"
        exit 0
    fi
    sleep 1
done

echo "❌ Port-forward 建立失敗"
rm -f /tmp/codimd-db-port-forward.pid
exit 1
