#!/bin/sh

set -eu

schedule_mode="${ALERT_MAIL_SCHEDULE_MODE:-disabled}"

case "$schedule_mode" in
  disabled)
    echo "Planificateur des mails d'alertes désactivé."
    exec tail -f /dev/null
    ;;
  test-5-min)
    schedule_label="toutes les 5 minutes"
    ;;
  weekdays-7-paris)
    schedule_label="du lundi au vendredi à 07:00 Europe/Paris"
    ;;
  *)
    echo "ALERT_MAIL_SCHEDULE_MODE invalide : $schedule_mode" >&2
    exit 1
    ;;
esac

if [ -z "${ALERT_MAIL_CRON_SECRET:-}" ]; then
  echo "ALERT_MAIL_CRON_SECRET est obligatoire." >&2
  exit 1
fi

if [ "${#ALERT_MAIL_CRON_SECRET}" -lt 32 ]; then
  echo "ALERT_MAIL_CRON_SECRET doit contenir au moins 32 caractères." >&2
  exit 1
fi

if [ -z "${BACKEND_INTERNAL_URL:-}" ]; then
  echo "BACKEND_INTERNAL_URL est obligatoire." >&2
  exit 1
fi

echo "Planificateur activé : $schedule_label."
echo "Groupes : ${ALERT_MAIL_SCHEDULE_GROUPS:-cisp}."

if [ "$schedule_mode" = "test-5-min" ]; then
  echo "Premier envoi de test au démarrage, puis toutes les 5 minutes."

  while true; do
    /app/run-alert-mail.sh || true
    sleep 300
  done
fi

echo "Surveillance de la fenêtre d'envoi de 07:00 à 07:09."

last_successful_date=""

while true; do
  current_weekday=$(date "+%u")
  current_hour=$(date "+%H")
  current_minute=$(date "+%M")
  current_date=$(date "+%F")

  if [ "$current_weekday" -le 5 ] \
    && [ "$current_hour" = "07" ] \
    && [ "$current_minute" -le 9 ] \
    && [ "$last_successful_date" != "$current_date" ]
  then
    if /app/run-alert-mail.sh; then
      last_successful_date="$current_date"
    else
      echo "L'envoi a échoué ; nouvelle tentative dans 30 secondes." >&2
    fi
  fi

  sleep 30
done
