#!/bin/sh
# init-license.sh — Activate Elasticsearch trial license after ES is ready.
# Runs once as a one-shot Docker service after elasticsearch is healthy.
#
# ES 8.14+ provides RRF at all license levels via the retriever API.
# Trial license unlocks additional platinum-tier features for 30 days.

set -e

ES_URL="http://zm-rag-es:9200"

echo "[init-license] Waiting for Elasticsearch at ${ES_URL} ..."
until curl -sf "${ES_URL}/_cluster/health" > /dev/null 2>&1; do
  echo "[init-license] ES not ready, retrying in 5s ..."
  sleep 5
done

echo "[init-license] Elasticsearch is up."

# Check current license type
CURRENT_TYPE=$(curl -sf "${ES_URL}/_license?filter_path=license.type" | sed -n 's/.*"type" *: *"\([^"]*\)".*/\1/p')
echo "[init-license] Current license type: ${CURRENT_TYPE}"

if [ "${CURRENT_TYPE}" = "trial" ] || [ "${CURRENT_TYPE}" = "enterprise" ] || [ "${CURRENT_TYPE}" = "platinum" ]; then
  echo "[init-license] License already sufficient (${CURRENT_TYPE}), skipping."
else
  echo "[init-license] Starting trial license ..."
  RESULT=$(curl -sf -X POST "${ES_URL}/_license/start_trial?acknowledge=true" 2>&1) || true
  echo "[init-license] Trial response: ${RESULT}"
fi

echo ""
echo "[init-license] Final license info:"
curl -sf "${ES_URL}/_license?filter_path=license.status,license.type,license.expiry_date"
echo ""
