#!/bin/sh
# One-shot bootstrap for the B2G logging stack. Idempotent — safe to re-run.
#   docker compose --profile setup up es-init
#
# Sets up, in Elasticsearch:
#   - ILM policy   b2g-logs-ilm   (delete indices after 14 days)
#   - index tmpl   b2g-logs       (keyword facets + ILM attachment)
#   - S3 repo      b2g-s3-archive (only if LOG_S3_BUCKET is set)
#   - SLM policy   b2g-daily-snap (daily snapshot of b2g-logs-* to S3)
# And in Kibana:
#   - data view + "B2G Backend Logs" dashboard (from ../kibana/export.ndjson)
set -eu

ES="${ES_URL:-http://elasticsearch:9200}"
KB="${KIBANA_URL:-http://kibana:5601}"
# ES security is enabled — authenticate every call as the elastic superuser.
AUTH="elastic:${ELASTIC_PASSWORD:-b2gElastic!2026}"

echo "==> Waiting for Elasticsearch at $ES ..."
until curl -fs -u "$AUTH" "$ES/_cluster/health" >/dev/null 2>&1; do sleep 3; done
echo "    Elasticsearch is up."

echo "==> Installing ILM policy b2g-logs-ilm"
curl -fs -u "$AUTH" -X PUT "$ES/_ilm/policy/b2g-logs-ilm" \
  -H 'Content-Type: application/json' \
  --data-binary @/es-init/ilm-policy.json >/dev/null
echo "    done."

# NOTE: the index template (index-template.json) is installed by LOGSTASH at
# pipeline startup (manage_template), so it always exists before the first
# document is indexed. It is intentionally not PUT here to avoid double ownership.

# ---- S3 cold-archive repository + daily snapshots (optional) ----
if [ -n "${LOG_S3_BUCKET:-}" ]; then
  # S3 setup is best-effort: a bad bucket/cred should warn, not abort the whole
  # bootstrap (the Kibana dashboard import below is more important).
  echo "==> Registering S3 snapshot repository b2g-s3-archive (bucket=$LOG_S3_BUCKET)"
  if curl -fs -u "$AUTH" -X PUT "$ES/_snapshot/b2g-s3-archive" \
      -H 'Content-Type: application/json' \
      -d "{
        \"type\": \"s3\",
        \"settings\": {
          \"bucket\": \"${LOG_S3_BUCKET}\",
          \"region\": \"${LOG_S3_REGION:-ap-south-1}\",
          \"base_path\": \"${LOG_S3_PREFIX:-b2g-logs}\"
        }
      }" >/dev/null; then
    echo "    repository registered."
    echo "==> Installing SLM policy b2g-daily-snap (daily 01:30, retain 90d)"
    curl -fs -u "$AUTH" -X PUT "$ES/_slm/policy/b2g-daily-snap" \
      -H 'Content-Type: application/json' \
      -d '{
        "schedule": "0 30 1 * * ?",
        "name": "<b2g-logs-{now/d}>",
        "repository": "b2g-s3-archive",
        "config": { "indices": ["b2g-logs-*"], "ignore_unavailable": true },
        "retention": { "expire_after": "90d" }
      }' >/dev/null && echo "    SLM policy installed." \
        || echo "    WARN: SLM policy install failed; continuing."
  else
    echo "    WARN: S3 repository registration failed (check LOG_S3_* creds/bucket/region)."
    echo "          Logs still index locally with 14-day ILM. Fix and re-run to enable S3."
  fi
else
  echo "==> LOG_S3_BUCKET not set — skipping S3 repository + SLM."
  echo "    (Logs still index locally with 14-day ILM. Set LOG_S3_* in docker/elk/.env"
  echo "     and re-run to enable the S3 cold archive.)"
fi

# ---- Kibana data view + dashboard ----
echo "==> Waiting for Kibana at $KB ..."
until curl -fs -u "$AUTH" "$KB/api/status" >/dev/null 2>&1; do sleep 3; done
echo "    Kibana is up."

NDJSON="/kibana/export.ndjson"
if [ -f "$NDJSON" ]; then
  echo "==> Importing Kibana saved objects (data view + dashboard)"
  curl -fs -u "$AUTH" -X POST "$KB/api/saved_objects/_import?overwrite=true" \
    -H "kbn-xsrf: true" \
    -F file=@"$NDJSON" >/dev/null && echo "    done."
else
  echo "    (skipping Kibana import — $NDJSON not mounted)"
fi

echo "==> Bootstrap complete."
