#!/bin/bash
################################################################################
#    HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
#
#    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.
################################################################################

INSTALL_DIR=/opt/HPCCSystems
CONFIG_DIR=/etc/HPCCSystems
ENV_XML_FILE=environment.xml
ENV_CONF_FILE=environment.conf
PID_DIR=/var/run/HPCCSystems
LOCK_DIR=/var/lock/HPCCSystems
LOG_DIR=/var/log/HPCCSystems
INIT_PATH=/etc/init.d


source ${INSTALL_DIR}/sbin/hpcc_setenv
deploydir=$(dirname $(type -path $0))

source  ${INSTALL_DIR}/etc/init.d/hpcc_common
component=$(basename $PWD)

PID_NAME="${PID_DIR}/${component}.pid"

timestamp="$(date +%Y_%m_%d_%H_%M_%S)"
export logfile="${LOG_DIR}/${component}/init_${component}_${timestamp}.log"

# for use by init_thorslave call
logredirect="init_thorslave_${component}_${timestamp}.log"

log "Starting ${component}"

log "removing any previous sentinel file"
export SENTINEL="thor.sentinel"
rm -f ${SENTINEL}

if [[ -z "$deploydir" ]]; then
    deploydir=$(pwd -P)
fi

instancedir=$(pwd -P)
source $instancedir/setvars
slaveportinc=$(($channelsperslave * $localthorportinc))

ln -s -f $deploydir/thormaster_lcr thormaster_$THORNAME

ENV_DIR=$(cat ${HPCC_CONFIG} | sed -n "/\[DEFAULT\]/,/\[/p" | grep "^configs=" | sed -e 's/^configs=//')

contains()
{
    local n=$#
    local value=${!n}
    local i=0
    for ((i=1;i < ${n};i++)); do
        if [[ "${!i}" == "${value}" ]]; then
            echo "${i}"
            return 0
        fi
    done
    echo "0"
    return 1
}

kill_slaves()
{
    log "Killing slaves"
    # NB: many of the parameters to init_thorslave not used by 'stop' command
    if [[ "$localthor" = "true" ]]; then
        $deploydir/init_thorslave stop localhost $slavespernode $THORSLAVEPORT $slaveportinc $THORMASTER $THORMASTERPORT $LOG_DIR $instancedir $deploydir $THORNAME ${INSTALL_DIR}/sbin $logredirect
    else
        # we want to kill only slaves that have already been started in run_thor
        if [[ -r $instancedir/uslaves ]]; then
            clusternodes=$(cat $instancedir/uslaves 2> /dev/null | wc -l)
            $deploydir/frunssh $instancedir/uslaves "/bin/sh -c '$deploydir/init_thorslave stop localhost $slavespernode $THORSLAVEPORT $slaveportinc $THORMASTER $THORMASTERPORT $LOG_DIR $instancedir $deploydir $THORNAME ${INSTALL_DIR}/sbin $logredirect'" -i:$SSHidentityfile -u:$SSHusername -pe:$SSHpassword -t:$SSHtimeout -a:$SSHretries -n:$clusternodes 2>&1
            FRUNSSH_RC=$?
            if [[ ${FRUNSSH_RC} -gt 0 ]]; then
                log "Error ${FRUNSSH_RC} in frunssh"
                log "Please check ${LOG_DIR}/frunssh for more details"
                # clean up any slaves it was able to reach
                log "Stopping ${component}"
                kill_process ${PID_NAME} thormaster_${component} 25
                rm -f $instancedir/slaves > /dev/null 2>&1
            else
                log "Frunssh successful"
            fi
        fi
    fi

    rm -f $instancedir/uslaves > /dev/null 2>&1
}

killed()
{
    log "Stopping ${component}"
    kill_process ${PID_NAME} thormaster_${component} 25
    log "$component Stopped"
    unlock ${LOCK_DIR}/$component/${component}.lock
    kill_slaves
    log "removing init.pid file and slaves file"
    rm -f $instancedir/slaves > /dev/null 2>&1
    exit 255
}

trap "killed" SIGINT SIGTERM
log "Ensuring a clean working environment ..."
kill_slaves
thorpid=0

while [[ 1 ]]; do
    # update slaves file in case state of environment has been altered since last run
    errorMessage=$( daliadmin server=$DALISERVER clusternodes ${component} $instancedir/slaves 2>&1 )
    errcode=$?
    if [[ 0 != ${errcode} ]]; then
        log "failed to lookup dali group for ${component}"
        log "$errorMessage"
        exit 1
    fi

    log "--------------------------"
    log "starting thorslaves ..."

    # Would be simpler, if there was simple way to test if ip is local and get rid of 'localthor' setting
    sort $instancedir/slaves | uniq > $instancedir/uslaves

    # To configure Thor to run with valgrind, set 'valgrindOptions' in the ThorCluster in the environment.xml
    # e.g. set valgrindOptions="--tool=memcheck --leak-check=full --show-leak-kinds=all -v"

    if [[ "$localthor" = "true" ]]; then
        slaveip=$(head -n 1 $instancedir/uslaves)
        $deploydir/init_thorslave start $slaveip $slavespernode $THORSLAVEPORT $slaveportinc $THORMASTER $THORMASTERPORT $LOG_DIR $instancedir $deploydir $THORNAME ${INSTALL_DIR}/sbin $logredirect "${valgrindOptions}"
    else
        clusternodes=$(cat $instancedir/uslaves | wc -l)
        escapedValgrindOptions=$(printf %q "$valgrindOptions")
        $deploydir/frunssh $instancedir/uslaves "/bin/sh -c '$deploydir/init_thorslave start %a $slavespernode $THORSLAVEPORT $slaveportinc $THORMASTER $THORMASTERPORT $LOG_DIR $instancedir $deploydir $THORNAME ${INSTALL_DIR}/sbin $logredirect ${escapedValgrindOptions}'" -i:$SSHidentityfile -u:$SSHusername -pe:$SSHpassword -t:$SSHtimeout -a:$SSHretries -n:$clusternodes 2>&1
        FRUNSSH_RC=$?
        if [[ ${FRUNSSH_RC} -gt 0 ]]; then
            log "Error ${FRUNSSH_RC} in frunssh"
            log "Please check ${LOG_DIR}/frunssh for more details"
            # clean up any slaves it was able to reach
            kill_slaves
            rm -f $instancedir/slaves > /dev/null 2>&1
            log "Sleeping for 30 seconds before retrying"
            sleep 30
            continue
        fi
    fi

    if [ -z ${valgrindOptions} ]; then
        log "thormaster cmd : $instancedir/thormaster_$THORNAME --master=$THORMASTER:$THORMASTERPORT"
        nohup $instancedir/thormaster_$THORNAME --master=$THORMASTER:$THORMASTERPORT 2> /dev/null 1>/dev/null &
    else
        cmd="valgrind ${valgrindOptions} --log-file=$LOG_DIR/$THORNAME/valgrind.thormaster.log $instancedir/thormaster_$THORNAME --master=$THORMASTER:$THORMASTERPORT 2>/dev/null 1>/dev/null &"
        log "${cmd}"
        eval ${cmd}
    fi

    thorpid=$!
    if [[ "$thorpid" -ne "0" ]]; then
        log "thormaster_lcr process started pid = $thorpid"

        echo $thorpid > $PID_NAME
        wait $thorpid
        errcode=$?
        case $errcode in
        # TEC_Clean
        0)  log "Thormaster ($thorpid) Exited cleanly"
            rm -f $instancedir/slaves $instancedir/uslaves $PID_NAME > /dev/null 2>&1
            exit 0
            ;;
        # TEC_CtrlC
        1)  log "Thormaster ($thorpid) Interrupted, Ctrl-C caught"
            killed
            ;;
        # TEC_SlaveInit
        4)  log "Thormaster ($thorpid) Slaves failed to initialize"
            log "Shutting down"
            killed
            ;;
        # TEC_Idle
        2)  log "Thormaster ($thorpid) Idle"
            kill_slaves
            ;;
        # TEC_Swap=5, TEC_Watchdog=3, TEC_DaliDown=6
        *)  if [[ $errcode -eq 5 ]]; then
                log "Thormaster ($thorpid) Swap node required"
            elif [[ $errcode -eq 3 ]]; then
                log "Thormaster ($thorpid) Lost connection to slave(s)"
            elif [[ $errcode -eq 6 ]]; then
                log "Thormaster ($thorpid) Unable to connect to Dali"
            else
                log "Thormaster ($thorpid) Unknown error code: [$errcode]"
            fi
            log "Stopping thorslave(s) for restart"
            kill_slaves
            if [[ "false" != "$autoSwapNode" ]]; then
              log "Running autoswap $THORNAME :: ($thorpid)"
              swapnode auto $DALISERVER $component
              errcode=$?
              if [[ 0 != ${errcode} ]]; then
                log "Auto swap node failed, errcode=${errcode}"
                killed
              fi
            else
              log "Autoswap set to false. Restarting"
            fi
            # restarting thormaster
            ;;
        esac
    else
        log "failed to start thormaster_lcr, pausing for 30 seconds"
        sleep 30
        kill_slaves
    fi
    if [[ ! -e $SENTINEL ]]; then
        log "$SENTINEL has been removed or thormaster did not fully start - script stopping"
        exit 0
    fi
done
