#!/bin/bash

##################################################
# Mount dir                                      #
# - /opt/kibana/config                           #
# - /opt/kibana/data                             #
# - /opt/kibana/logs                             #
# - /opt/kibana/offline-plugins                  #
# - /opt/kibana/plugins                          #
# ENV                                            #
# - _CONF_*                                      #
# - NODE_OPTIONS                                 #
##################################################

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 node && Print killing node ... || break
        sleep 1
    done
    Print Container stopped.
    test -n "$GOT_SIGTERM"
}

function Usage {
    Print 'This container should run with
    **root user**
    **/opt/kibana/{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 {
    local kv=
    local conf='config/kibana.yml'
    Print Modifying $conf ...
    while read kv; do
        [ -z "$kv" ] && break
        sed -i "/^${kv%%=*}: /d" $conf
        echo "${kv/=/: }" >> $conf
    done <<< "$(env | grep '^_CONF_' | sed 's/_CONF_//')"
}

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

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

function StartProc {
    Print Starting kibana ...
    su - kibana -c "
        export NODE_OPTIONS='${NODE_OPTIONS:-}'
        /opt/kibana/bin/kibana
    " &>> logs/kibana.out &
    PIDS="$PIDS $!"
    Print Kibana started.
}

function Main {
    local pid=
    cd /opt/kibana
    Usage
    RestoreConf
    ModifyConf
    InstallPlugin
    ChangeOwner
    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

