#!/usr/bin/env bash
# Runs supervisord (Reverb + queue worker) on cPanel without sudo.
#
#   deploy/cpanel/supervisor.sh              start supervisord unless it is already running (cron calls this)
#   deploy/cpanel/supervisor.sh status       any other arguments go to supervisorctl:
#   deploy/cpanel/supervisor.sh restart all  status, restart reverb, tail -f reverb, stop all, shutdown...
set -euo pipefail

# The PHP CLI that runs artisan. Must be 8.3+. If `php -v` over SSH shows an
# older version, point this at cPanel's binary, e.g. /opt/cpanel/ea-php83/root/usr/bin/php
PHP_BIN="${PHP_BIN:-/opt/cpanel/ea-php84/root/usr/bin/php}"

export PATH="$HOME/.local/bin:$PATH"
export PHP_BIN
export APP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
CONF="$APP_DIR/deploy/cpanel/supervisord.conf"
PIDFILE="$APP_DIR/storage/logs/supervisor/supervisord.pid"

if [ $# -gt 0 ]; then
  exec supervisorctl -c "$CONF" "$@"
fi

if [ -f "$PIDFILE" ] && kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then
  exit 0
fi

if ! "$PHP_BIN" -r 'exit(PHP_VERSION_ID >= 80300 ? 0 : 1);'; then
  echo "PHP_BIN ($PHP_BIN) is missing or older than 8.3; set PHP_BIN in $0" >&2
  exit 1
fi

# If the host killed only supervisord, its old Reverb still holds port 8080
# and the new one could never bind it.
pkill -f "$APP_DIR/artisan (reverb:start|queue:work)" || true

mkdir -p "$APP_DIR/storage/logs/supervisor"
exec supervisord -c "$CONF"
