#!/usr/bin/env sh
set -eu

ROOT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)"
PYTHON_BIN="${PYTHON_BIN:-$ROOT_DIR/.venv/bin/python}"
DJANGO_SETTINGS_MODULE="${DJANGO_SETTINGS_MODULE:-rad.settings}"
RESTART_DELAY="${RESTART_DELAY:-3}"
MAX_RESTARTS="${MAX_RESTARTS:-0}"

if [ ! -x "$PYTHON_BIN" ]; then
  echo "Python binary not found or not executable: $PYTHON_BIN" >&2
  exit 1
fi

export DJANGO_SETTINGS_MODULE

restart_count=0

echo "Starting persistent db_worker loop"
echo "Root: $ROOT_DIR"
echo "Settings: $DJANGO_SETTINGS_MODULE"
echo "Python: $PYTHON_BIN"

while true; do
  echo "[$(date -u +%Y-%m-%dT%H:%M:%SZ)] Launching db_worker"
  if "$PYTHON_BIN" "$ROOT_DIR/manage.py" db_worker; then
    exit_code=0
  else
    exit_code=$?
  fi

  echo "[$(date -u +%Y-%m-%dT%H:%M:%SZ)] db_worker exited with code $exit_code"
  if [ "$exit_code" -eq 137 ] || [ "$exit_code" -eq 9 ]; then
    echo "[$(date -u +%Y-%m-%dT%H:%M:%SZ)] db_worker appears to have been SIGKILL'ed (likely OOM)." >&2
  fi

  if [ "$MAX_RESTARTS" -gt 0 ] && [ "$restart_count" -ge "$MAX_RESTARTS" ]; then
    echo "Max restarts reached ($MAX_RESTARTS). Exiting." >&2
    exit "$exit_code"
  fi

  restart_count=$((restart_count + 1))
  echo "Restarting in ${RESTART_DELAY}s (restart #$restart_count)"
  sleep "$RESTART_DELAY"
done
