#!/bin/sh
#
# VYNDR API container entrypoint.
#
# Boots the PM2-managed pollers in daemon mode, then execs the Express
# server in the foreground so it runs as PID 1 (which Docker's signal
# forwarding + healthcheck expect). PM2 daemonizes its supervisor inside
# the container; the pollers keep running while Express handles requests.
#
# On container restart (Coolify redeploy) PM2's state is gone — that's
# fine, this script reseeds it. Pollers are idempotent: status keys live
# in Redis with TTLs, so a restart at most re-processes one game.
#
# Why a separate file from scripts/start.sh: that one is the local-dev
# launcher (boots the Python NBA service + Node API in the host shell).
# This one is the production container entrypoint.

set -e

# PM2 needs a writable HOME for its run-dir. The vyndr non-root user
# can't write to /root, so park PM2's metadata in /app/.pm2.
export PM2_HOME="${PM2_HOME:-/app/.pm2}"
mkdir -p "$PM2_HOME"

echo "[docker-entrypoint] PM2_HOME=$PM2_HOME"
echo "[docker-entrypoint] booting pollers via PM2"
cd /app/poller
pm2 start ecosystem.config.js || \
  echo "[docker-entrypoint] PM2 start failed — continuing without pollers so the API still serves"
pm2 list || true

cd /app
echo "[docker-entrypoint] starting Express server (PID 1)"
exec node src/server.js
