#!/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.
################################################################################
#
#########################################################################
#                                                                       #
#                          System Flow                                  #
#                                                                       #
#########################################################################
#                                                                       #
#      1. Parse Passed In arguments                                     #
#      2. Get the component and specific information                    #
#      3. Generate component related config files (runtime directory)   #
#      4. CD to the runtime Directory                                   #
#      5. Start the component                                           #
#                                                                       #
#########################################################################

##-----------------------------------------------------------------------------
#                         chkconfig Parameters
##-----------------------------------------------------------------------------

### BEGIN INIT INFO
# chkconfig: 235 40 90
# Description: Starts the HPCC processes
# Short-Description: Controls HPCC Processes
# Provides: hpcc-init
# Required-Start: dafilesrv
# Required-Stop:
# Default-Start:
# Default-Stop:
### END INIT INFO

##-----------------------------------------------------------------------------
#                         General Purpose Functions                           
##-----------------------------------------------------------------------------

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



function print_usage {
    echo "Usage: $0 [-c component] {start|stop|restart|status|setup}
       $0 [--componentlist] Display node component name list.
       $0 [--typelist] Display node component type list.
       $0 [-f] [--force] Force hard kill on orphaned process groups
       $0 [-h] [--help] Display help"
    echo
    print_components
    exit 0
}

function print_components {
    if [ ! -z ${compList} ];then
        echo  "Components on this node as defined by ${CONFIG_DIR}/${ENV_XML_FILE}:"
        IFS=$'\n'
        echo  "${compList[*]}"
        unset IFS
    else
        echo  "No components on this node as defined by ${CONFIG_DIR}/${ENV_XML_FILE}."
    fi
    echo
    exit 0
}

function print_types {
    if [ ! -z ${compList} ];then
        echo  "Components types on this node as defined by ${CONFIG_DIR}/${ENV_XML_FILE}:"
        IFS=$'\n'
        echo  "${compTypeList[*]}"
        unset IFS
    else
        echo  "No components on this node as defined by ${CONFIG_DIR}/${ENV_XML_FILE}."
    fi
    echo
    exit 0
}


cfggenpre=()

source  ${INSTALL_DIR}/etc/init.d/lock.sh
source  ${INSTALL_DIR}/etc/init.d/pid.sh
source  ${INSTALL_DIR}/etc/init.d/hpcc_common
source  ${INSTALL_DIR}/etc/init.d/init-functions
source  ${INSTALL_DIR}/etc/init.d/export-path

export logfile=${LOG_DIR}/hpcc-init.log

createDir ${LOG_DIR}
[ ! -e ${logfile}  ] && touch $logfile

## Debug variable allowing verbose debug output
##
DEBUG=${DEBUG:-NO_DEBUG}
TRACE=${TRACE:-0}
VERBOSE=${VERBOSE:-0}
COMP_BY_TYPE=${COMP_BY_TYPE:-0}
DAFILESRV=${DAFILESRV:-0}
FORCE=${FORCE:-NO_FORCE}

set_environmentvars
envfile=$configs/$environment

# Know HPCC user after set_environmentvars
log_dir_owner=$(ls -ld $LOG_DIR | awk '{print $3}')
[ "log_dir_owner" != "${user}" ] && chown ${user}:${group} $LOG_DIR
chown ${user}:${group} $logfile

#Sourcing the hpcc environment
configgen_path=${path}/sbin
bin_path=${path}/bin
source ${configgen_path}/hpcc_setenv

which_service

log "--------------------------"
log "--------------------------"

#Check for existance of user
check_user ${user}
if [ $? -ne 1 ];then
   log  "User ${user} does not exist on the system. Exiting ..."
   echo "User ${user} does not exist on the system. Exiting ..."
   exit 3
fi

check_group ${group}
if [ $? -ne 1 ];then
   log  "Group ${group} does not exist on the system or not able to chgrp (sudo?). Exiting ..."
   echo "Group ${group} does not exist on the system or not able to chgrp (sudo?). Exiting ..."
   exit 3
fi

check_getopt

basepath=`pwd`

COMPS=$(${configgen_path}/configgen -env ${envfile} -list)
rc=$?
if [[ $rc -ne 0 ]]; then
    log "hpcc-init: failure to build COMPS from configgen call"
    echo -e "\033[31merror\033[0m: hpcc-init -> failure to build COMPS from configgen call"
    exit 1
fi

comp.parser ${COMPS}

if [ -z ${compArray} ];then
   log  "There are no components configured to run on this node ..."
   echo "There are no components configured to run on this node ..."
   exit 3
fi

#--------------------------------------------------------------------------------
#                                    Beginning of the Option Parsing                                                 
#-------------------------------------------------------------------------------

compList[0]=''
compListLen=0
compTypeList[0]=''
foundThorSlave=0
compDafilesrv=''

#Forming the component list from the configgen 

for i in ${compArray[@]}; do
    compName=${i#*_}
    comp.getByName ${compName}
    componentType=`echo ${comp_return} | awk -F" " '{print $1}' | awk -F"=" '{print $2}'`
    if [ -z ${compName} ];
    then
        continue;
    elif strstr ${componentType} "dali" ;
    then
        compDali=${compName}
    elif strstr ${componentType} "thor";
    then
        comp.getByName "${compName}"
        if strstr ${comp_return} "slave";
        then
            foundThorSlave=1
        fi
        compListLen=$(expr ${compListLen} + 1)
        compList[${compListLen}]=${compName}
        compTypeList[${compListLen}]=${componentType}
    else
        if strstr ${componentType} "ftslave" ; 
        then 
            continue
        elif strstr ${componentType} "dafilesrv";
        then
            compDafilesrv=${compName}
        else
            compListLen=$(expr ${compListLen} + 1)
            compList[${compListLen}]=${compName}
            compTypeList[${compListLen}]=${componentType}
        fi
    fi
done

#Defaulting the first component as Dali 
compList[0]=$compDali
compTypeList[0]="dali"

log "The following components have been located:"
for i in ${compList[@]};do
    log "---> $i"
done
log "--------------------------"
    
#declaring all flags here
isComp=0
component=""
runSetupOnly=0
dafilesrvflag=0

TEMP=`getopt -o c:hdf --long help,componentlist,typelist,debug,force -n 'hpcc-init' -- "$@"`
if [ $? != 0 ] ; then echo "Failure to parse commandline." >&2 ; exit 1 ; fi
eval set -- $TEMP
while true ; do
    case "$1" in
        -c) comp=$2
            isComp=1
            comp.getByName $comp
            if [ -z $comp_return ] ;
            then
                comp.getByType $comp
                if [ -z $comp_return ]
                then
                    log "Unknown component: $comp"
                    echo "Unknown component: $comp"
                    exit 1
                fi
                for (( i=0; i<=${compListLen}; i++ ));do
                    if strstr ${compTypeList[$i]} "$comp";
                    then
                        component="$component ${compList[$i]}"
                    fi
                done
                if [ -z "${component}" ];then
                   if strstr "${comp}" "dafilesrv" ;then
                       component="${component} ${compDafilesrv}"
                   fi
                fi
            else
                component=$comp
            fi
            shift 2 ;;
        -d|--debug) DEBUG="DEBUG"
                    shift ;;
        -f|--force) FORCE="FORCE"
                    shift ;;
        -h|--help)  print_usage
                    shift ;;
        --componentlist) print_components
                    shift ;;
        --typelist) print_types
                    shift ;;
        --) shift ; break ;;
        *) print_usage ;;
    esac
done
for arg do arg=$arg; done

if [ -z $arg ] || [ $# -ne 1 ]; then
    print_usage
fi

thisos=$(uname -s)
if [[ "$thisos" = "Linux" && -f "${envfile}" && -n "${component}" && \
    "${DEBUG}" = "NO_DEBUG" && -z "$HPCC_NO_FLOCK" ]] ; then
    cfggenpre=(flock ${envfile})
fi

# verbose output of all shell cmds to .debug file only if -d specified on cmdline
if [[ "${DEBUG}" != "NO_DEBUG" ]] ; then
    log "Debug log written to $LOG_DIR/hpcc-init.debug"
    [ -e $LOG_DIR/hpcc-init.debug ] && rm -rf ${LOG_DIR}/hpcc-init.debug
    touch ${LOG_DIR}/hpcc-init.debug
    chown ${user}:${group} ${LOG_DIR}/hpcc-init.debug
    PS4='+\011$(date "+%T.%N")\011'
    exec 3>&2 2>$LOG_DIR/hpcc-init.debug
    set -x
fi

if [ -z "${component}" ]; then
    for (( i=0; i<=${compListLen}; i++ ));do
        component="$component ${compList[$i]}"
    done
elif strstr ${component} "dafilesrv";then
    compDafilesrv=${component}
    component=''
else
    compDafilesrv=''
fi

case "$arg" in 
    status|start|restart|setup)
        cmd=$arg
        ;;
    stop)
       #need to reverse the list so that dali stops last
       cmd=$arg
       component_rev=""
       if [ "${isComp}" -eq 0 ]; then
         for (( i=${compListLen}; i>=0; i-- ));
         do
            if strstr ${compList[$i]} "dafilesrv" ;then
              continue;
            fi
            component_rev="$component_rev ${compList[$i]}"
         done
         if [ ! -z "${component_rev}" ]; then
            component=${component_rev}
         fi   
       fi
       ;;
    *) print_usage
        ;;
esac

log "Attempting to execute ${cmd} argument on specified components"


# Create dropzone on a full system start
if [ "${cmd}" = "start" ] || [ "${cmd}" = "restart" ]; then
    validate_configuration
    get_commondirs
    log "Creating dropzone"
    create_dropzone
fi

unset IFS
#Before we start/stop any component we should check dafilesrv.
if [ ! -z "${compDafilesrv}" ];then
    case "$1" in
        start)
            ${INIT_PATH}/dafilesrv status 1>/dev/null 2>/dev/null
            if [ $? -ne 0 ];then
              log "--------------------------"
              log "${compDafilesrv} ---> ${cmd}"
              ${INIT_PATH}/dafilesrv $1 2>/dev/null
            else
              log  "Dependent service dafilesrv, ${compDafilesrv} is already running."
              echo "Dependent service dafilesrv, ${compDafilesrv} is already running."
            fi
            ;;
        status|setup)
            ${INIT_PATH}/dafilesrv ${1} 2>/dev/null
            ;;
        stop|restart)
            ;;
    esac
fi

# Restart handling for entire system
if [ ${cmd} = "restart" ] && [ "${isComp}" -eq 0 ]; then
    log "Stopping entire system for a full restart"
    log "--------------------------"
    echo "*****************************************"
    echo "Stopping entire system for a full restart"
    echo "*****************************************"
    cmd=stop
    statForStop=0;
    for (( i=${compListLen}; i>=0; i-- ));do
        if [ -z "${compList[$i]}" ];then
          continue;
        fi
        set_componentvars ${compList[$i]}
        xcmd="${cmd}_component ${compList[$i]}"
        log "--------------------------"
        log "${compName} ---> ${cmd}"
        if strstr ${compType} "thor" && [ ${foundThorSlave} -eq 1 ];
        then
            log "Thor slave found on the node, hence skipping the component "
            continue
        elif strstr ${compType} "dafilesrv" ;then
            log "skipping the component ${compName}"
            continue;
        else
          eval $xcmd
          statForEach=$?
          log "${xcmd} ---> Exit status ${statForEach}"
          statForStop=$(( ${statForStop} == 3 ? ${statForEach} : ${statForStop} ))
        fi
    done 

    log "Starting the entire System"
    log "--------------------------"
    echo "***************************************************"
    echo "Starting the entire System"
    echo "***************************************************"
    cmd=start
    ${INIT_PATH}/dafilesrv status 1>/dev/null 2>/dev/null
    if [ $? -ne 0 ];then
        log "--------------------------"
        log "${compDafilesrv} ---> ${cmd}"
        ${INIT_PATH}/dafilesrv $1 2>/dev/null
    fi

    statForStart=0
    for (( i=0; i<=${compListLen}; i++ ));do
        if [ -z "${compList[$i]}" ];then
           continue;
        fi
        set_componentvars ${compList[$i]}
        xcmd="${cmd}_component ${compList[$i]}"
        log "--------------------------"
        log "${compName} ---> ${cmd}"
        if strstr ${compType} "thor" && [ ${foundThorSlave}  -eq 1 ]; 
        then
            log "Thor slave found on the node, hence just running the setup for thor"
            setup_component
            continue
        else
           eval $xcmd
           statForEach=$?
           log "${xcmd} ---> Exit status ${statForEach}"
           statForStart=$(( ${statForStart} == 0 ? ${statForEach} : ${statForStart} ))
        fi
    done
    if [ "${statForStop}" -eq 3 ] && [ "${statForStart}" -eq 0 ];
    then
        exit 0
    else
       a=$(( ${statForStop} != 0  ? $statForStop : $statForStart ))
       exit $a
    fi
fi

# All other command handling
# start, stop and status (individual component restart as well)
STATUS=0
for C in ${component} ; do
    if [ -z "${C}" ];then
      continue;
    fi
    set_componentvars ${C}
    xcmd="${cmd}_component ${C}"
    if strstr ${compType} "thor" && [ ${foundThorSlave} -eq 1 ] && [ "${cmd}" != "status" ] && [ "${cmd}" != "setup" ]; then
      log "Thor slave found on the node, hence just running the setup for thor"
      setup_component
      continue
    else
      log "--------------------------"
      log "${compName} ---> ${cmd}"
      eval $xcmd
      statForEach=$?
      log "${cmd}_component ${C} ---> Exit status ${statForEach}"
      STATUS=$(( $STATUS == 0 ? $statForEach : $STATUS))
    fi
done 


if [ "$cmd" = "stop" ] && [ -n "$compDafilesrv" ]
then
    ${INIT_PATH}/dafilesrv status 1>/dev/null 2>/dev/null
    if [ $? -ne 0 ];then
      log  "Service dafilesrv, ${compDafilesrv} is already stopped."
      echo "Service dafilesrv, ${compDafilesrv} is already stopped."
    else
      log  "Service dafilesrv, ${compDafilesrv} is still running."
      echo "Service dafilesrv, ${compDafilesrv} is still running."
      echo "To stop it, run \"/etc/init.d/dafilesrv stop\"."
    fi

fi
exit ${STATUS}
