#!/bin/bash

################################################################################
#
# This script starts the ElasticSearch single node cluster locally on port 9200
#
################################################################################

###
# if script dir is not specified, set it to cuurent dir
if [ $# == 1 ]
then
  SCRIPT_DIR="$1"
else
  SCRIPT_DIR="."
fi


if [ "$#" -ne 2 ]
then
  echo
  echo "****************************************"
  echo "Usage:: $0  <script-dir> <schema-file>"
  echo "****************************************"
  exit 1
fi

SCRIPT_DIR="$1"
MAPPINGS_DEFINITION_FILE="$2"

###
# Fail fast
set -eau pipefail

###
# which python3 : Depends on the OS
PYTHON_CMD='/usr/bin/python3' # first preference is standard Ubuntu location
if [ ! -x ${PYTHON_CMD} ]
then
  PYTHON_CMD='/usr/local/bin/python3' # For MacOS
  if [ ! -x ${PYTHON_CMD} ]
  then
    echo
    echo "****************************************"
    echo "python3 is not available"
    echo "****************************************"
    exit 1
  fi
fi

###
# Set common vars
. ${SCRIPT_DIR}/es_container_vars.sh

###
# Execute clean up (just in case previous run was aborted etc)
${SCRIPT_DIR}/stop_es_local.sh ${SCRIPT_DIR}

###
# pull the docker image if needed
echo
echo "==================== Pulling docker image for ElasticSearch"
docker pull "${ES_IMAGE_TAG}"

###
# Start the docker image in the background with output redirected to a tmp file
echo
echo "==================== Starting docker container for ElasticSearch"
docker run -p 9200:9200 -p 9300:9300 \
    -e "discovery.type=single-node" \
    --name ${ES_CONTAINER_NAME} \
    "${ES_IMAGE_TAG}" &> "${ES_LOG_FILE}" &


max_tries=5
current_try=0
container_status="false"
sleep_for=1
while (( current_try < max_tries ))
do
  echo "    .... sleeping for ${sleep_for} seconds"
  sleep ${sleep_for}
  ((sleep_for=2*sleep_for))
  echo "    .... checking if docker container is running"
  container_status=$(docker inspect -f '{{.State.Running}}' ${ES_CONTAINER_NAME} 2>&1 || true)
  echo "    .... container status is ${container_status}"
  if [ "true" == "${container_status}" ] ; then break; fi
  ((current_try=current_try + 1))
  if (( current_try >= max_tries ))
  then
    echo
    echo "******************** FAILED TO ENSURE THAT DOCKER CONTAINER HAS STARTED ********************"
    echo
    exit 1
  fi
done

###
# Create indices and apply mappings to match the production cluster
echo
echo "==================== Applying production schema to ElasticSearch"
${PYTHON_CMD}  ${SCRIPT_DIR}/create_doc_schema.py \
    --elastic_search_host "${ES_HOST}" \
    --elastic_search_port "${ES_PORT}" \
    --elastic_search_use_ssl "${ES_USE_SSL}" \
    --mappings_definition_file ${MAPPINGS_DEFINITION_FILE}

