#!/bin/sh
set -e

# 1. Initialize workspace
mkdir -p /workspace/.cw
echo '{"version":1}' > /workspace/.cwrc

# 2. Git globals
git config --global user.email "preview@codewalkers.dev"
git config --global user.name "Codewalkers Preview"
git config --global protocol.file.allow always
git config --global init.defaultBranch main

# 3. Start backend
cd /workspace
CW_DB_PATH=/workspace/.cw/cw.db node /app/apps/server/dist/bin/cw.js --server &
BACKEND_PID=$!

# 4. Wait for health
echo "Waiting for backend to start..."
TRIES=0
MAX_TRIES=60
until curl -sf http://localhost:3847/health > /dev/null 2>&1; do
  TRIES=$((TRIES + 1))
  if [ "$TRIES" -ge "$MAX_TRIES" ]; then
    echo "Backend failed to start after ${MAX_TRIES}s"
    exit 1
  fi
  sleep 1
done
echo "Backend is healthy"

# 5. Run Caddy in foreground (receives signals)
exec caddy run --config /etc/caddy/Caddyfile
