#!/bin/sh # docker-entrypoint.sh — Polaris Task Force container entrypoint (PID 1). # Always starts the web server (CMD: node server.js, received as "$@"). # Starts the Discord bot (`node --import tsx src/bot/index.ts`) ONLY when # DISCORD_TOKEN is set (Coolify per-environment activation gate; dev/stage # leave it unset). # # The bot is SUPERVISED: if it exits, the exit is logged and it is restarted # with capped exponential backoff (5s .. 60s). This closes the old silent-death # gap where a crashed bot left the unit with no bot while the web app stayed # healthy. The web server owns the container's lifetime: when it exits, the # supervisor is stopped and the container exits with the web server's status. # SIGTERM/SIGINT are forwarded to both children. BOT_RESTART_INITIAL_SECONDS=5 BOT_RESTART_MAX_SECONDS=60 BOT_SUPERVISOR_PID="" # Restart loop for the bot. Runs in a subshell so the parent keeps waiting on # the web server; on shutdown the parent signals this subshell, whose trap # stops the current bot child and exits. supervise_bot() { bot_child="" trap 'if [ -n "$bot_child" ]; then kill -TERM "$bot_child" 2>/dev/null; wait "$bot_child" 2>/dev/null; fi; exit 0' TERM INT delay=$BOT_RESTART_INITIAL_SECONDS attempt=0 while :; do attempt=$((attempt + 1)) node --import tsx src/bot/index.ts & bot_child=$! wait "$bot_child" bot_status=$? bot_child="" echo "[entrypoint] Discord bot exited (status ${bot_status}) on attempt ${attempt}; restarting in ${delay}s" >&2 sleep "$delay" delay=$((delay * 2)) [ "$delay" -le "$BOT_RESTART_MAX_SECONDS" ] || delay=$BOT_RESTART_MAX_SECONDS done } # 1) Web server (owns the container lifetime). "$@" & WEB_PID=$! # 2) Discord bot (only when the activation gate is open), supervised. if [ -n "${DISCORD_TOKEN:-}" ]; then echo "[entrypoint] DISCORD_TOKEN is set — starting supervised Discord bot" >&2 supervise_bot & BOT_SUPERVISOR_PID=$! else echo "[entrypoint] DISCORD_TOKEN is not set — Discord bot disabled" >&2 fi # 3) Forward shutdown signals to both children. forward() { signal=$1 [ -z "$WEB_PID" ] || kill -"$signal" "$WEB_PID" 2>/dev/null || true [ -z "$BOT_SUPERVISOR_PID" ] || kill -"$signal" "$BOT_SUPERVISOR_PID" 2>/dev/null || true } trap 'forward TERM' TERM trap 'forward INT' INT # 4) Wait for the web server; exit with its status. while kill -0 "$WEB_PID" 2>/dev/null; do wait "$WEB_PID" status=$? done # 5) Web server gone: stop the bot supervisor, then exit. if [ -n "$BOT_SUPERVISOR_PID" ]; then kill -TERM "$BOT_SUPERVISOR_PID" 2>/dev/null || true wait "$BOT_SUPERVISOR_PID" 2>/dev/null || true fi exit "${status:-0}"