#!/usr/bin/env bash

echo -e "Elasticsearch (type $suffix):"
if [ "$(ls elasticsearch/idx$suffix)" ]; then
  echo -e "${COLORED}\tNo need to rebuild${NC}"
  exit 10
fi

docker-compose -f ../../docker-compose.yml --env-file ../../.env stop elasticsearch
docker-compose -f ../../docker-compose.yml --env-file ../../.env rm -f elasticsearch
mkdir -p elasticsearch/idx$suffix
chmod -R 777 elasticsearch/idx$suffix # otherwise elasticsearch in docker won't start
chmod -R 777 data          # otherwise logstash may not be able to read the files
cmd="test=$test suffix=$suffix docker-compose -f ../../docker-compose.yml --env-file ../../.env up -d elasticsearch"
echo -e "\tStarting elasticsearch ($cmd)"
eval "$cmd"
echo -e "\tWaiting for elasticsearch to come up"

if timeout 60 grep -qm1 'Cluster health status changed from \[YELLOW\] to \[GREEN\]' <(docker logs -f elasticsearch_engine); then
  echo -e '\tAccepting connections';
else
  echo -e '\tElasticsearch failed to start properly in 60 seconds';
  exit 1
fi


