#!/bin/bash

##################################################
# Mount dir                                      #
# - /opt/logstash/config                         #
# - /opt/logstash/data                           #
# - /opt/logstash/logs                           #
# - /opt/logstash/offline-plugins                #
##################################################

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**
    **/opt/logstash/{config,data,logs,offline-plugins} mounted from host**
    '
}

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

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

function StartProc {
    Print Starting logstash ...
    ./bin/logstash \
        --path.data /opt/logstash/data \
        --path.logs /opt/logstash/logs \
        --path.settings /opt/logstash/config \
        &>> logs/logstash.out &
    PIDS="$PIDS $!"
    Print Logstash started.
}

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

