#!/usr/bin/env bash
set -e

APP_ROLE="${APP_ROLE:-web}"

# Run pending migrations before starting any role.
python manage.py migrate --noinput

if [ "$APP_ROLE" = "scheduler" ]; then
  NEWSLETTER_SCHEDULER_INTERVAL_SECONDS="${NEWSLETTER_SCHEDULER_INTERVAL_SECONDS:-${SCHEDULER_INTERVAL_SECONDS:-60}}"
  CONTACT_SCHEDULER_INTERVAL_SECONDS="${CONTACT_SCHEDULER_INTERVAL_SECONDS:-60}"

  run_newsletter_loop() {
    while true; do
      if ! python manage.py run_newsletter_scheduler --limit 20; then
        echo "newsletter scheduler command failed" >&2
      fi
      sleep "$NEWSLETTER_SCHEDULER_INTERVAL_SECONDS"
    done
  }

  run_contact_loop() {
    while true; do
      if ! python manage.py run_contact_submission_worker; then
        echo "contact submission worker command failed" >&2
      fi
      sleep "$CONTACT_SCHEDULER_INTERVAL_SECONDS"
    done
  }

  run_newsletter_loop &
  newsletter_pid=$!
  run_contact_loop &
  contact_pid=$!

  stop_scheduler_loops() {
    kill "$newsletter_pid" "$contact_pid" 2>/dev/null || true
    wait "$newsletter_pid" "$contact_pid" 2>/dev/null || true
  }
  trap stop_scheduler_loops EXIT TERM INT
  wait
else
  python manage.py collectstatic --noinput
  exec "$@"
fi
