#!/usr/bin/env sh
#
# xrootd/cmsd   This shell script takes care of starting and stopping
#               Qserv xrootd/cmsd instances.
# description: xrootd is the filesystem which allow Qserv master to \
# communicate with Qserv workers.\
# It is composed of two services : xrootd and cmsd

### BEGIN INIT INFO
# Provides: xrootd cmsd
# Short-Description: start and stop xrootd/cmsd
# Description: XRootD software framework is a fully generic suite for fast, \
#              low latency and scalable data access. It's the communication \
#              middleware used between Qserv master and nodes. \
### END INIT INFO

DIR=$(cd "$(dirname "$0")"; pwd -P)

# Source functions library.
. ${DIR}/qserv-functions

NAME="xrootd"
DAEMON=${NAME}

XRLOG=/tmp/xrootd.init.log
touch $XRLOG

echo "daemon $DAEMON  dir $DIR" >> $XRLOG

source_sysconfig ${DIR}

echo "node_t $NODE_TYPE  dir $DIR" >> $XRLOG

# Check variables which are not controlled by application
check_writable ${NAME} "QSERV_RUN_DIR"
check_writable ${NAME} "QSERV_PID_DIR"
check_writable ${NAME} "QSERV_LOG_DIR"
check_readable ${NAME} "XROOTD_DIR"


err_msg="Failure while starting ${NAME}:"
if [ -z "${NODE_TYPE}" ]
then
    log_failure_msg "${local_err_msg} \$NODE_TYPE is an empty string"
    exit 1
elif [ "${NODE_TYPE}" = "mono" ]
then
    XROOTD_INSTANCE_NAME="worker"
	XRD_SERVICES="xrootd"
else
    XROOTD_INSTANCE_NAME="$NODE_TYPE"
	XRD_SERVICES="xrootd cmsd"
fi

XROOTD_CONFIG="${QSERV_RUN_DIR}/etc/lsp.cf"
# Add configuration for xrdssi, used only on Qserv workers, not Czar
XRDSSI_CONFIG="${QSERV_RUN_DIR}/etc/xrdssi.cnf"

PID_DIR=${QSERV_PID_DIR}/${XROOTD_INSTANCE_NAME}
LOG_DIR=${QSERV_LOG_DIR}

# Log configuration file for worker nodes.
# xrootd manager doesn't use it.
# Indeed, log4cxx is only used by Qserv plugin
# which only runs on xrootd server side (i.e. worker nodes)
export LSST_LOG_CONFIG="${QSERV_RUN_DIR}/etc/log4cxx.worker.properties"

# method to guess pid file name,
# takes single argument - program name
pid_file_name() {
    local pidfile=${PID_DIR}/$1.pid
    test "${1}${NODE_TYPE}" = "cmsdmaster" && pidfile=${PID_DIR}/$1.mangr.pid
    test "${1}${NODE_TYPE}" = "cmsdmaster-shared" && pidfile=${PID_DIR}/$1.mangr.pid
    echo $pidfile
}

# Environment variables can vary from on container session to another and making them 
# reliably consistent is difficult. Instead, use "mangr.pid" version if that file exists,
# otherwise use the ".pid" file version.
pid_file_name_check() {
    local pf=${PID_DIR}/$1.mangr.pid
    if [ ! -f "$pf" ]; then
        pf=${PID_DIR}/$1.pid
    fi
    echo $pf
}

echo "node_type=$NODE_TYPE" >> $XRLOG
echo "instance=$XROOTD_INSTANCE_NAME" >> $XRLOG
echo "services=$XRD_SERVICES" >> $XRLOG
echo "pid_dir=$PID_DIR" >> $XRLOG
echo "log_dir=$LOG_DIR" >> $XRLOG

start_service() {

    local prog

    prog=${1##*/}

    pidfile=$(pid_file_name $prog)
    lockfile=${QSERV_RUN_DIR}/var/lock/subsys/${prog}
    BINARY=${XROOTD_DIR}/bin/${prog}
    logfile=@libXrdSsiLog.so
    [ -x ${BINARY} ] || exit 5
    [ -f ${XROOTD_CONFIG} ] || exit 6

    console_logfile="${LOG_DIR}/xrootd.log"
    cmd="${BINARY} -c ${XROOTD_CONFIG} -l ${logfile} -n ${XROOTD_INSTANCE_NAME} -I v4  -+xrdssi ${XRDSSI_CONFIG} >>${console_logfile} 2>&1 &"
    echo "pidfile=$pidfile"  >> $XRLOG
    echo "lockfile=$lockfile"  >> $XRLOG
    echo "cmd=$cmd" >> $XRLOG
    start -p ${pidfile} -l ${lockfile} ${prog} "${cmd}"
    ret=$?
    # xrootd modifies log file path, try to guess it here too for logging
    # purpose
    real_logfile=${LOG_DIR}/${XROOTD_INSTANCE_NAME}/${prog}.log
    [ $ret -eq 0 ] || echo "See startup logfiles : ${console_logfile}, ${real_logfile}"
    return $ret
}

stop_service() {

    local prog

    prog=${1##*/}

    pidfile=$(pid_file_name_check $prog)
    lockfile=${QSERV_RUN_DIR}/var/lock/subsys/${prog}

    stop -p $pidfile -l $lockfile $prog
}

start_all() {
    mkdir -p ${PID_DIR} || {
        log_failure_msg "Failed to create ${PID_DIR}"
        return 1
    }

    ret_val=0
	for service in $XRD_SERVICES
	do
        start_service "$service" || ret_val=1
	done
	return "$ret_val"
}

stop_all() {
    ret_val=0
	for service in $XRD_SERVICES
	do
        stop_service "$service" || ret_val=1
	done
	return "$ret_val"

}

status_all () {
    ret_val=0
	for service in $XRD_SERVICES
	do
        DAEMON="${XROOTD_DIR}/bin/${service}"
		pidfile=$(pid_file_name_check $service)
		status_of_proc -p $pidfile "$DAEMON" "$service" || ret_val=1
	done
	return "$ret_val"
}



# See how we were called.
case "$1" in
    start)
        start_all
        ;;
    stop)
        stop_all
        ;;
    status)
        status_all
        ;;
    restart)
        stop_all
        start_all
        ;;
    try-restart|condrestart)
        if status_all > /dev/null; then
            stop_all
            start_all
        fi
        ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|try-restart}"
        exit 2
esac
