#!/bin/bash

##################################################
# Docker                                         #
# -- privileged                                  #
# Mount dir                                      #
# - /opt/es/config                               #
# - /opt/es/data                                 #
# - /opt/es/logs                                 #
# - /opt/es/offline-plugins                      #
# - /opt/es/plugins                              #
# ENV                                            #
# - _CONF_*                                      #
# - ES_JAVA_OPTS                                 #
##################################################

set -euo pipefail
export LANG=en_US.UTF-8
trap Quit EXIT

PIDS=
GOT_SIGTERM=

function Print {
    local file=/dev/null
    [ '-f' = "$1" ] && file=$2 && shift && shift
    date +"[%F %T] $*" | tee -a $file
}

function Quit {
    while :; do
        pkill -f java && Print killing java ... || break
        sleep 1
    done
    Print Container stopped.
    test -n "$GOT_SIGTERM"
}

function Usage {
    Print 'This container should run with
    **root user**
    **privileted**
    **/opt/es/{config,data,logs,offline-plugins,plugins} mounted from host**
    '
}

function RestoreConf {
    if [ -z "$(ls config/)" ]; then
        Print Restoring default config files and quit ...
        tar zxf config.tgz
        exit
    fi
}

function ModifyConf {
    Print Modifying $conf ...
    local kv=
    local conf='config/elasticsearch.yml'
    while read kv; do
        [ -z "$kv" ] && break
        sed -i "/^${kv%%=*}: /d" $conf
        echo "${kv/=/: }" >> $conf
    done <<< "$(env | grep '^_CONF_' | sed 's/_CONF_//')"
    Print Removing path.data and path.log in $conf ...
    sed -i -e '/^path\.data/d' -e '/^path\.logs/d' $conf
}

function InstallPlugin {
    for f in $(ls -d offline-plugins/*.zip 2>/dev/null); do
        Print Installing plugins from offline file: $f ...
        ./bin/elasticsearch-plugin install file://$f
        mv $f $f.installed
    done
}

function ChangeOwner {
    Print Changing file owner ...
    chown -R es:es config/ data/ logs/ plugins/
}

function ChangeSysConf {
    Print Changing system conf ...
    echo 262144 > /proc/sys/vm/max_map_count || Print Not specified "--privileged".
}

function StartProc {
    Print Starting elasticsearch ...
    su - es -c "
        export JAVA_HOME=$JAVA_HOME
        export PATH=$PATH
        export ES_JAVA_OPTS='${ES_JAVA_OPTS:-}'
        /opt/es/bin/elasticsearch -Epath.data=/opt/es/data -Epath.logs=/opt/es/logs
    " &> /dev/null &
    PIDS="$PIDS $!"
    Print Elasticsearch started.
}

function Main {
    local pid=
    cd /opt/es
    Usage
    RestoreConf
    ModifyConf
    InstallPlugin
    ChangeOwner
    ChangeSysConf
    StartProc
    trap "GOT_SIGTERM=1; Print Got SIGTERM ..." SIGTERM
    while [ -z "$GOT_SIGTERM" ] && sleep 2; do
        for pid in $PIDS; do
            [ ! -e /proc/$pid ] && Print Unexpected error! && exit
        done
    done
}

# Start here
Main

