#!/bin/sh
set -e

cd /app

echo "Contents of /app:"
ls

if [ ! -f server.js ]; then
  echo "ERROR: /app/server.js not found. Check your Docker COPY paths."
  exit 1
fi

# Save the main PORT for Go API (Dokku sets this)
API_PORT="${PORT:-5000}"

# Start Next.js admin on internal port 3001
echo "Starting Next.js admin on :3001..."
HOSTNAME="0.0.0.0" PORT=3001 NODE_ENV=production node server.js &
NODE_PID=$!

# Give Next.js a moment to boot
sleep 3

# If Node crashed immediately, bail out so you can see the logs
if ! kill -0 "$NODE_PID" 2>/dev/null; then
  echo "ERROR: Next.js server process exited. Check logs above for stack trace."
  exit 1
fi

# Start Go API on main PORT that Dokku expects
echo "Starting Go API on :${API_PORT}..."
export PORT="${API_PORT}"
exec /app/api
