#!/bin/bash

mode=${MODE:-x}

mkdir -p /esbackup
chown -R elasticsearch.elasticsearch /esbackup
case $mode in
  x)

    if [ ! -d "/esdata/data/nodes" ];then
       mkdir -p /esdata/logs
       mkdir -p /esdata/data
       chown -R elasticsearch.elasticsearch /esdata
    fi

    \cp  /usr/local/elasticsearch/config/elasticsearch.yml_single /usr/local/elasticsearch/config/elasticsearch.yml
     chmod +x /usr/local/elasticsearch/es_single_backup.sh
     service cron start
     (crontab -l 2>/dev/null; echo '00 03 * * * (flock -xn /usr/local/elasticsearch/run.lock -c "bash /usr/local/elasticsearch/es_single_backup.sh")') | crontab -

   ;;
  cluster)
     if [ ! -d "/esdata/data/nodes" ];then
       mkdir -p /esdata/logs
       mkdir -p /esdata/data
       chown -R elasticsearch.elasticsearch /esdata
     fi

   \cp  /usr/local/elasticsearch/config/elasticsearch.yml_cluster /usr/local/elasticsearch/config/elasticsearch.yml
   sed -i "s#NODE_NAME#${NODE_NAME}#g" /usr/local/elasticsearch/config/elasticsearch.yml
   ;;
esac

#export ES_PATH_CONF=/esdata/config

su elasticsearch -c "./bin/elasticsearch"
