#!/usr/bin/env sh
elastic_url=${ELASTICSEARCH_URL:-http://elasticsearch:9200}
elastic_user=${ELASTIC_USER:-elastic}
elastic_password=${ELASTIC_PASSWORD:-changeme}
elastic_auth=$elastic_user:$elastic_password

wait_loops=20
wait_sleep=3
count=0
while ! [ $(curl --write-out %{http_code} --silent --output /dev/null -u $elastic_auth $elastic_url/_cat/health?h=st) = 200 ]; do
    count=`expr $count + 1`
    if [ $count -ge $wait_loops ]; then
        echo "$(date) - still not ready, giving up"
        exit 1
    fi
    echo "$(date) - waiting to be ready"
    sleep $wait_sleep
done

uri_norm=$elastic_url/_component_template/normalized_component
uri_index=$elastic_url/_index_template/normalized

if ! [ $(curl --write-out %{http_code} --silent --output /dev/null -u $elastic_auth "$uri_norm") = 200 ]; then
  curl -X PUT -w "\n" -u $elastic_auth "$uri_norm" -H "Content-Type: application/json" -d"$(cat cmd/correlator/tests/mapping/normalized-component.json)"
else echo "Normalized component already mapped"; fi

if ! [ $(curl --write-out %{http_code} --silent --output /dev/null -u $elastic_auth "$uri_index") = 200 ]; then
  curl -X PUT -w "\n" -u $elastic_auth "$uri_index" -H "Content-Type: application/json" -d"$(cat cmd/correlator/tests/mapping/normalized-index-template.json)" 
else echo "Index normalized already mapped"; fi

exec "$@"
