#!/bin/sh
# ElastAlert 2 entrypoint:
#   1. render the SMTP auth file from environment (kept out of source control),
#   2. create ElastAlert's writeback index if missing (idempotent),
#   3. run ElastAlert.
set -eu

# SMTP credentials -> auth file the email alerter reads (referenced by the rule).
cat > /tmp/smtp_auth.yaml <<EOF
user: "${SMTP_USER:-}"
password: "${SMTP_PASSWORD:-}"
EOF
chmod 600 /tmp/smtp_auth.yaml

if [ -z "${ALERT_TO:-}" ] || [ -z "${SMTP_HOST:-}" ]; then
  echo "elastalert: WARNING — ALERT_TO / SMTP_HOST not set. Rules will still run and"
  echo "            DETECT bursts, but emails cannot be delivered until you set the"
  echo "            SMTP_* / ALERT_* vars in the root .env. See docker/elk/README.md."
fi

echo "elastalert: ensuring writeback indices exist..."
# create-index doesn't read es_host / env-vars from the config, so pass connection
# args explicitly. It is a no-op recreate if the indices already exist.
elastalert-create-index \
  --host elasticsearch --port 9200 \
  --username elastic --password "${ELASTIC_PASSWORD}" \
  --no-ssl --index elastalert_status --old-index "" 2>&1 | tail -3 || \
  echo "elastalert: create-index step skipped/failed (continuing)."

echo "elastalert: starting rule engine..."
exec elastalert --config /opt/elastalert/config.yaml --verbose
