#!/bin/bash
# LifeKeeper Web Management Console server start script.

LKDEFAULT="/etc/default/LifeKeeper"
LKROOT=${LKROOT:-/opt/LifeKeeper}
WEBUI_BASE_PATH=/opt/LifeKeeper
WEBUI_BIN=${WEBUI_BASE_PATH}/bin/lkWMC

cmd=$(basename "$0")

# Exit code 5 prevents systemd from trying to immediately restart the lifekeeper-wmc service
# See RestartPreventExitStatus in lifekeeper-wmc.service
EXIT_NO_SERVICE_RESTART=5

# LKWMC Log file path
WEBUI_LOGFILE="/var/log/lkwmc.log"

# function

logmsg () {
    echo "$(date +'%a %d %b %Y %T %Z') $(hostname) LkWMC[$$]: INFO:$cmd:::016999:$@" | tee -a $WEBUI_LOGFILE
}

# main

logmsg "Starting LifeKeeper Web Management Console server ($0)"

# Load /etc/default/LifeKeeper
if [ -f $LKDEFAULT ]
then
    . $LKDEFAULT
else
    logmsg "Defaults file at $LKDEFAULT is not found."
fi

# gather $WEBUI_BIN pids
pid=`ps -eo pid,cmd | grep $WEBUI_BIN | grep -v 'grep' | awk '{ print $1 }' | tr $'\n' ' ' | sed 's/[[:space:]]*$//'`

if [ -n "$pid" ]
then
	logmsg "LifeKeeper Web Management Console server is already running (PIDs: $pid). Aborting..."
	exit $EXIT_NO_SERVICE_RESTART
fi

# Config
WEBUI_DEFAULT_CONF=${WEBUI_BASE_PATH}/config/wmc-config.ini
config=${WEBUI_CONF_PATH:-${WEBUI_DEFAULT_CONF}}

# Port
RESTAPI_DEFAULT_PORT=5000
WEBUI_DEFAULT_PORT=5110
VALID_PORT_MIN=1
VALID_PORT_MAX=65535

api_port=${RESTAPI_PORT:-${RESTAPI_DEFAULT_PORT}}
if ! [[ "$api_port" =~ ^[0-9]+$ ]] || [[ "$api_port" -lt "$VALID_PORT_MIN" ]] || [[ "$api_port" -gt "$VALID_PORT_MAX" ]]
then
	logmsg "Invalid value \"$api_port\" specified for RESTAPI_PORT in /etc/default/LifeKeeper. Please specify an integer in the range $VALID_PORT_MIN-$VALID_PORT_MAX. Using default TCP port $RESTAPI_DEFAULT_PORT instead."
	api_port=$RESTAPI_DEFAULT_PORT
fi

gui_port=${WEBUI_PORT:-${WEBUI_DEFAULT_PORT}}
if ! [[ "$gui_port" =~ ^[0-9]+$ ]] || [[ "$gui_port" -lt "$VALID_PORT_MIN" ]] || [[ "$gui_port" -gt "$VALID_PORT_MAX" ]]
then
	logmsg "Invalid value \"$gui_port\" specified for WEBUI_PORT in /etc/default/LifeKeeper. Please specify an integer in the range $VALID_PORT_MIN-$VALID_PORT_MAX. Using default TCP port $WEBUI_DEFAULT_PORT instead."
	gui_port=${WEBUI_DEFAULT_PORT}
fi

if [[ "$api_port" -eq "$gui_port" ]]
then
    logmsg "The same value was specified for RESTAPI_PORT and WEBUI_PORT ($gui_port). Aborting..."
    exit $EXIT_NO_SERVICE_RESTART
fi

# SSL
CERTDIR=$LKROOT/etc/certs
PEMFILE=$CERTDIR/LK4LinuxValidNode.pem
use_ssl=${WEBUI_USE_SSL:-true}
cert_file=${WEBUI_SSL_CERT_FILE:-${PEMFILE}}
key_file=${WEBUI_SSL_CERT_KEY_FILE:-${PEMFILE}}
if [ "$use_ssl" = true ] && [ -e $cert_file ]  && [ -e $key_file ]; then
    SSLOPT="--ssl --cert=$cert_file --key=$key_file"
fi

# DEBUG
debug_webui=${DEBUG_WEBUI:-${DEBUG}}
if [ -n "$debug_webui" ] && [ "$debug_webui" != "0" ]; then
    DEBUGOPT="--debug"
fi

exec $WEBUI_BIN --port $gui_port --backend_port $api_port --config $config --log $WEBUI_LOGFILE $SSLOPT $DEBUGOPT