#!/usr/bin/env bash
set -u
set -o pipefail

stop_requested=0
stop_status=0
worker_pid=0
beat_pid=0
web_pid=0
direct_web=0

log() {
  printf '[%s] %s\n' "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$*"
}

terminate_children() {
  local worker="$worker_pid" beat="$beat_pid" web="$web_pid" pid
  worker_pid=0 beat_pid=0 web_pid=0
  for pid in "$worker" "$beat" "$web"; do
    if ((pid)); then kill -TERM "$pid" 2>/dev/null || true; fi
  done
}

shutdown() {
  if ((direct_web)); then exit "$1"; fi
  if ((!stop_requested)); then
    stop_requested=1 stop_status="$1"
    terminate_children
  fi
}

reap_children() {
  trap '' SIGTERM SIGINT
  log "shutdown requested; waiting for child processes"
  wait || true
}

trap 'shutdown 143' SIGTERM
trap 'shutdown 130' SIGINT

exec_if_running() {
  # The background subshell inherits a stop that arrived just before fork.
  if ((!stop_requested)); then exec "$@"; fi
}

restart_delay="${REPROQ_RESTART_DELAY_SECONDS:-5}"
prestart_cmd="${REPROQ_PRESTART_CMD:-}"
custom_prestart=0
if [[ -n "$prestart_cmd" ]]; then
  custom_prestart=1
fi
prestart_interval="${REPROQ_PRESTART_INTERVAL_SECONDS:-5}"
prestart_max_wait="${REPROQ_PRESTART_MAX_WAIT_SECONDS:-120}"
worker_cmd="${REPROQ_WORKER_CMD:-}"
case "${REPROQ_WORKER_ENABLED-true}" in
  "1"|[Tt][Rr][Uu][Ee]) worker_enabled=1 ;;
  "0"|[Ff][Aa][Ll][Ss][Ee]) worker_enabled=0 ;;
  *)
    log "REPROQ_WORKER_ENABLED must be true, false, 1, or 0."
    exit 1
    ;;
esac
default_beat=0
scheduler_mode_normalized="$(printf '%s' "${REPROQ_SCHEDULER_MODE:-}" | tr '[:upper:]' '[:lower:]' | xargs)"
if [[ -v REPROQ_BEAT_CMD ]]; then
  beat_cmd="${REPROQ_BEAT_CMD}"
  beat_cmd_normalized="$(printf '%s' "$beat_cmd" | tr '[:upper:]' '[:lower:]' | xargs)"
  case "$beat_cmd_normalized" in
    ""|"0"|"false"|"off"|"disabled"|"none")
      beat_cmd=""
      ;;
  esac
else
  beat_cmd=""
  default_beat=1
fi
web_cmd="${REPROQ_WEB_CMD:-}"

if [[ -n "$scheduler_mode_normalized" && "$scheduler_mode_normalized" != "beat" ]]; then
  log "non-beat scheduler mode; disabling reproq-beat."
  beat_cmd=""
  default_beat=0
fi

if [[ -z "$web_cmd" ]]; then
  log "REPROQ_WEB_CMD is required (set it to your web process command)."
  exit 1
fi

if [[ -z "$prestart_cmd" || ( "$worker_enabled" -eq 1 && -z "$worker_cmd" ) || "$default_beat" -eq 1 ]]; then
  # One selected runtime serves all default commands. Login shells may reset
  # PATH, so retain its absolute interpreter rather than another UV parent.
  if [[ -n "${VIRTUAL_ENV:-}" ]]; then
    selected_python="${VIRTUAL_ENV}/bin/python"
  elif ! selected_python="$(uv run python -c 'import sys; print(sys.executable)')"; then
    log "could not resolve the default command interpreter with uv"
    exit 1
  fi
  if [[ "$selected_python" != /* || ! -x "$selected_python" ]]; then
    log "the selected default command interpreter must be an executable absolute path"
    exit 1
  fi
  printf -v python_command '%q' "$selected_python"
  if [[ -z "$prestart_cmd" ]]; then
    prestart_cmd="exec ${python_command} manage.py reproq check"
  fi
  if [[ "$worker_enabled" -eq 1 && -z "$worker_cmd" ]]; then
    worker_cmd="exec ${python_command} manage.py reproq worker --concurrency ${REPROQ_CONCURRENCY:-3} --metrics-addr ${METRICS_ADDR:-127.0.0.1:9090}"
  fi
  if [[ "$default_beat" -eq 1 ]]; then
    beat_cmd="exec ${python_command} manage.py reproq beat --interval ${REPROQ_BEAT_INTERVAL:-30s}"
  fi
fi

run_prestart() {
  if ((custom_prestart)); then
    bash -lc "$prestart_cmd" >/dev/null 2>&1
  else
    bash -lc "$prestart_cmd"
  fi
}

if [[ -n "$prestart_cmd" ]]; then
  log "prestart checking"
  prestart_started=$(date +%s)
  while (( ! stop_requested )); do
    prestart_status=0
    run_prestart || prestart_status=$?
    if ((stop_requested)); then
      break
    fi
    if ((prestart_status == 0)); then
      log "prestart ok"
      break
    fi
    now=$(date +%s)
    elapsed=$((now - prestart_started))
    if [[ "${prestart_max_wait}" -gt 0 && "${elapsed}" -ge "${prestart_max_wait}" ]]; then
      log "prestart failed after ${elapsed}s"
      exit 1
    fi
    log "prestart failed; retrying in ${prestart_interval}s"
    sleep "${prestart_interval}"
  done
fi

run_with_restart() {
  local name="$1"
  local cmd="$2"
  local child_pid=0 exit_code

  terminate_child() {
    local pid="$child_pid"
    child_pid=0
    if ((pid)); then kill -TERM "$pid" 2>/dev/null || true; fi
  }

  wait_for_child() {
    local pid="$1" status=0
    child_pid="$pid"
    if ((stop_requested)); then terminate_child; fi
    wait "$pid" || status=$?
    child_pid=0
    if ((stop_requested)); then
      trap '' SIGTERM SIGINT
      wait "$pid" 2>/dev/null || true
    fi
    return "$status"
  }

  trap 'stop_requested=1; terminate_child' SIGTERM SIGINT

  while ((!stop_requested)); do
    log "${name} starting"
    if ((stop_requested)); then break; fi
    exec_if_running bash -lc "$cmd" &
    wait_for_child "$!"
    exit_code=$?
    if ((stop_requested)); then break; fi
    log "${name} exited with ${exit_code}; restarting in ${restart_delay}s"
    if ((stop_requested)); then break; fi
    exec_if_running sleep "${restart_delay}" &
    wait_for_child "$!" || true
  done
  log "${name} stopped"
}

start_actor() {
  local pid_variable="$1"
  shift
  if ((!stop_requested)); then
    run_with_restart "$@" &
    printf -v "$pid_variable" '%d' "$!"
    if ((stop_requested)); then terminate_children; fi
  fi
}

if ((stop_requested)); then
  log "prestart canceled"
  exit 1
fi

if [[ "$worker_enabled" -eq 1 ]]; then
  start_actor worker_pid "reproq-worker" "REPROQ_PROCESS_ROLE=worker ${worker_cmd}"
else
  log "reproq-worker disabled (REPROQ_WORKER_ENABLED=false)"
fi

if [[ -n "$beat_cmd" ]]; then
  start_actor beat_pid "reproq-beat" "REPROQ_PROCESS_ROLE=beat ${beat_cmd}"
else
  log "reproq-beat disabled (empty REPROQ_BEAT_CMD)"
fi

if ((stop_requested)); then
  reap_children
  exit "$stop_status"
fi

if ((!worker_pid && !beat_pid)); then
  # No actor needs a restart supervisor; retain the web command's exit/signal
  # behavior without an otherwise idle parent process.
  direct_web=1
  if ((stop_requested)); then exit "$stop_status"; fi
  log "web starting"
  exec bash -lc "REPROQ_PROCESS_ROLE=web ${web_cmd}"
fi

log "web starting"
if ((stop_requested)); then
  reap_children
  exit "$stop_status"
fi
exec_if_running bash -lc "REPROQ_PROCESS_ROLE=web ${web_cmd}" &
web_process=$!
web_pid="$web_process"
if ((stop_requested)); then
  terminate_children
  web_status="$stop_status"
else
  wait "$web_process"
  web_status=$? web_pid=0
fi

shutdown 0
reap_children
if ((stop_status)); then exit "$stop_status"; fi
exit "${web_status}"
