#!/bin/bash
# ============================================
# Switchboard Core - Backend Launcher
# ============================================
# Runs as an nginx entrypoint.d hook.
# Starts the Go backend in the background
# before nginx begins accepting connections.
# ============================================

set -e

# Inject BASE_PATH into frontend HTML/JS at runtime
if [ -n "${BASE_PATH}" ]; then
    echo "🔧 Injecting BASE_PATH=${BASE_PATH} into frontend assets..."
    find /usr/share/nginx/html -type f \( -name '*.html' -o -name '*.js' \) \
        -exec sed -i "s|%%BASE_PATH%%|${BASE_PATH}|g" {} +
else
    # No prefix — strip the placeholder entirely
    find /usr/share/nginx/html -type f \( -name '*.html' -o -name '*.js' \) \
        -exec sed -i "s|%%BASE_PATH%%||g" {} +
fi

echo "🔀 Starting Switchboard Core backend..."

# Kill any stale backend from a previous entrypoint run
pkill -f /usr/local/bin/switchboard 2>/dev/null || true
sleep 0.2

# Launch Go backend in background (from /app so migrations are found)
cd /app
/usr/local/bin/switchboard &
BACKEND_PID=$!

# Wait for backend to be ready (max 60s)
for i in $(seq 1 120); do
    if wget -q --spider http://localhost:${PORT:-8080}${BASE_PATH}/health 2>/dev/null; then
        echo "✅ Backend ready (PID ${BACKEND_PID})"
        exit 0
    fi
    # Check backend didn't crash
    if ! kill -0 ${BACKEND_PID} 2>/dev/null; then
        echo "❌ Backend process died"
        exit 1
    fi
    sleep 0.5
done

echo "❌ Backend failed to start within 60s"
kill ${BACKEND_PID} 2>/dev/null || true
exit 1
