#!/bin/bash -e

source "logging"

ES_CLUSTER_HOST=${ES_CLUSTER_HOST:-"localhost"}
ES_CLUSTER_PORT=${ES_CLUSTER_PORT:-9300}
MAX_WAIT_SEED=${MAX_WAIT_SEED:-$((60*60*24*7))} #one week

NODES=$(es_util --query=_cat/nodes | wc -l)
if [ $NODES -ge 2 ] ; then
  SECURITY_SHARDS=1
else
  SECURITY_SHARDS=0
fi

info "Seeding the security ACL index.  Will wait up to $MAX_WAIT_SEED seconds."

function sgadmin {
  secadmincmd=${ES_HOME}/plugins/openshift-elasticsearch/sgadmin.sh
  if [ -f ${ES_HOME}/plugins/opendistro_security/tools/securityadmin.sh ] ; then
    secadmincmd=${ES_HOME}/plugins/opendistro_security/tools/securityadmin.sh
  fi
  $secadmincmd \
    -i $( get_security_conf_index ) \
    -h ${ES_CLUSTER_HOST} \
    -p ${ES_CLUSTER_PORT} \
    -ks ${ES_PATH_CONF}/secret/admin.jks \
    -kst JKS \
    -kspass kspass \
    -ts ${ES_PATH_CONF}/secret/truststore \
    -tst JKS \
    -tspass tspass \
    -nhnv \
    -arc \
    -icl \
    -er $SECURITY_SHARDS \
    ${DEBUG:+-dg} ${@:-}
}

MAX_WAIT_SEED=${MAX_WAIT_SEED:-$((60*60*24*7))} #one week

info "Seeding the security ACL index.  Will wait up to $MAX_WAIT_SEED seconds."

now=0
numretries=0
loginterval=${SG_ADMIN_LOG_INTERVAL:-100}
while ! sgadmin -cd ${HOME}/sgconfig && [ ${now} -lt ${MAX_WAIT_SEED} ]
do
    if ! expr $numretries % $loginterval ; then
        warn "Error seeding the security ACL index... retrying in 10 seconds - $numretries retries so far"
        warn "Seeding will continue to fail until the cluster status is YELLOW"
        info "Remaining red indices: $(QUERY=_cat/indices es_util | grep "^red" | wc -l)"
    fi
    numretries=$((numretries+1))
    sleep 10
    now=$((now+40)) #wait plus 30s timeout from sgadmin
done

if [ ${now} -ge ${MAX_WAIT_SEED} ]; then
    error "Giving up trying to seed ACL"
    exit 1
fi
info "Seeded the security ACL index"
