#!/bin/bash

# Copyright: 2023 Virtuozzo International GmbH

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

# http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


export LC_ALL=en_US.UTF-8
export MANAGE_VERSION="1";
export MANAGE_PROGRAM_NAME="jem";
export MANAGE_BINARY_NAME="$0";
export MANAGE_KILL_TARGET="$$";

export MANAGE_DATA_PATH="${MANAGE_DATA_PATH:="/usr/lib/jelastic"}";
export MANAGE_DEFAULT_MODULES_PATH="${MANAGE_DATA_PATH}/modules";
export MANAGE_MODULES_PATH=($MANAGE_DEFAULT_MODULES_PATH);
export MANAGE_CORE_PATH="${MANAGE_CORE_PATH:="/usr/lib/jelastic/libs"}";
export MANAGE_DEFAULT_ACTIONS="${MANAGE_CORE_PATH}/default.lib";
export MANAGE_APP_TEMPLATES="${MANAGE_APP_TEMPLATES:="/usr/lib/jelastic/tpls"}";

DEBUG=${DEBUG:="0"};


export META_FILE="/etc/jelastic/metainf.conf";
export JEM_CALLS_LOG="${JEM_CALLS_LOG:="/var/log/jem.log"}";

[[ "x$1" == "xisolation" ]] && export JEM_CALLS_LOG="/var/log/jem-isolation.log"
[[ "x$1" == "xhn" ]] && export JEM_CALLS_LOG="/var/log/jem-hn.log"

export FIRST_RUN_SCENARIO="/var/lib/jelastic/firstrun";
export PATH="/usr/local/sbin:/bin:/sbin:/usr/bin:/usr/sbin";

echo -n `date +%D.%k:%M:%S.%N` >> ${JEM_CALLS_LOG} 2>&1;
echo ":[EXEC]      [PID: $$] $@" >> ${JEM_CALLS_LOG} 2>&1;

SUDO_CMD=""
[[ "$(id -u)" != "0" ]] && SUDO_CMD="sudo"

$SUDO_CMD chmod 666 $JEM_CALLS_LOG;
$SUDO_CMD chmod 555 /usr/bin/jem;
find /usr/lib/jelastic -type d -print0 | xargs -0 $SUDO_CMD chmod 0755;
find /usr/lib/jelastic -type f -print0 | xargs -0 $SUDO_CMD chmod 0644;

"unalias" -a;
unset -f rm;
unset CDPATH GLOBIGNORE;
IFS=$' \t\n';

shopt -s extglob;
shopt -s expand_aliases;

source "${MANAGE_CORE_PATH}/core.lib" || exit 255;
inherit output path-manip tests;
trap '{ stopJemThreadQueueManager ; exit 250; }' 15;
trap '{ exit 0; } ' USR1;

function _manageDoUsage() {
        echo "Usage: jem <global options> <module name> <module options>";
}

function _manageDoHelp() {
        setOutputMode default;
        _manageDoUsage;
        echo "Options are:";
        _manageDoListOptions;
        echo "Modules are:";
        _manageDoListModules;
        echo
}

function _manageFindModule() {
        local modname="$1" modpath="" modfile="";
        [[ -z ${modname} ]] && die "Usage: ${FUNCNAME} <module>";
        for modpath in "${MANAGE_MODULES_PATH[@]}"; do
                [[ -f ${modpath}/${modname}.module ]] && break;
        done

        modfile="${modpath}/${modname}.module"
        [[ -r ${modfile} ]] || {
            local message="Can't load module ${modname}"
            >&2 echo "$message"
            die -q "$message";
        }
        echo ${modfile}
}

function _manageDoListOptions() {
        echo "Global options:";
        echo -e "\t--brief\t\tMake output shorter\n";
}

function _manageDoListModules() {
        doAction modules List "$@";
}

function executeFirstRunScenario() {
    [ -f $FIRST_RUN_SCENARIO ]  && bash $FIRST_RUN_SCENARIO > /dev/null 2>&1 && rm -f $FIRST_RUN_SCENARIO;
}

[[ -z ${action} ]] && {
    action=$1;
    shift;
}

#do not perform any operation if container not fully started
if [[ ! -e /dev/vzctl && $UID == 0 ]] ; then
    pcount=10
    while [[ $pcount -gt 0 ]] ; do
        [[ -e /proc/1/exe ]] && ! readlink -f /proc/1/exe | grep -q vzctl && break
        echo "`date +%D.%k:%M:%S.%N`: no proc/1/exe" >> $JEM_CALLS_LOG
        sleep 0.5
        pcount=$((pcount-1))
    done

    if readlink -f /proc/1/exe | grep -qE 'systemd/systemd' ; then
        count=10
        while [[ $count -gt 0 ]] ; do
            out=$(systemctl is-system-running 2>&1 )
            if [[ "x$out" == "xstarting" || "x$out" == "xinitializing" ]] ; then
                count=$((count-1))
                sleep 1
            elif grep -q D-Bus <<< $out; then
                sleep 1
            else
                count=0
            fi
            echo "`date +%D.%k:%M:%S.%N`:   $action:$subaction - waiting start $count, status: $out" >> $JEM_CALLS_LOG
        done
    else
        echo "`date +%D.%k:%M:%S.%N`: not systemd system $(readlink -f /proc/1/exe)" >> $JEM_CALLS_LOG
    fi
fi

startJemThreadQueueManager "$@";
executeFirstRunScenario;
if [[ -n ${action} ]] ; then
    if isFunction "_manageDo${action//-/_}"; then
        [[ $# -gt 0 ]] && die -q "Too many parameters";
        _manageDo${action//-/_};
    else
        doAction "${action}" "$@"
    fi
else
    _manageDoUsage;
fi

result=$?
stopJemThreadQueueManager;
exit $result;
