#!/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 30 80
# Description: Starts the HPCC dafilesrv processes
# Short-Description: Controls HPCC dafilesrv
# Provides: dafilesrv
# Required-Start:
# 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 >&2 "Usage: $0 {start|stop|restart|status|setup}
        $0 [-h] [--help]"
    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

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

configgen_path=${INSTALL_DIR}/sbin
basepath=`pwd`
set_environmentvars
envfile=$configs/$environment
bin_path=${INSTALL_DIR}/bin

component=""
runSetupOnly=0
source ${configgen_path}/hpcc_setenv
createDir ${LOG_DIR}

which_service

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

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

check_getopt

COMPS=$(${configgen_path}/configgen -env ${envfile} -ip "127.0.0.1" -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}
for i in ${compArray[@]}; do
    compName=${i#*_}
    comp.getByName ${compName}
    compType=`echo $comp_return | cut -d ' ' -f 1 | cut -d '=' -f 2 `
    if strstr ${compType} "dafilesrv" ;
    then
        component=${compName}
        break
    fi
done


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

if [ -z "${component}" ] ; then
    log_failure_msg "dafilesrv is not configured to run on this node"
    exit 3
fi

TEMP=`getopt -o h --long help -n 'dafilesrv' -- "$@"`
if [ $? != 0 ] ; then echo "Failure to parse commandline." >&2 ; exit 1 ; fi
eval set -- $TEMP
while true ; do
    case "$1" in
        -h|--help) print_usage
                   shift ;;
        --) shift ; break ;;
        *) print_usage ;;
    esac
done
for arg do arg=$arg; done

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

# for starting hpcc components concurrently, as
# configgen -validateonly does not create unique tempdirs
thisos=$(uname -s)
if [[ "$thisos" = "Linux" && -f "${envfile}" && -n "${component}" && \
    "${DEBUG}" = "NO_DEBUG" && -z "$HPCC_NO_FLOCK" ]] ; then
    cfggenpre=(flock ${envfile})
fi

case "$arg" in
    status|start|restart|stop|setup)
        cmd=$arg
        ;;
    *) print_usage
        ;;
esac

if [ "${cmd}" = "start" ] || [ "${cmd}" = "restart" ]; then
    validate_configuration
fi

unset IFS

DAFS_LOCK="/tmp/dafs_lock"
trap "rm -f $DAFS_LOCK" SIGINT SIGTERM SIGQUIT
STATUS=0

for C in ${component} ; do
    set_componentvars ${C}
    if [ "${cmd}" == "start" ];then
       xcmd="${cmd}_dafilesrv ${C}"
    else
       xcmd="${cmd}_component ${C}"
    fi
    if [ ${DEBUG} != "NO_DEBUG" ]; then
        echo $xcmd
    fi
    if [[ "${cmd}" == "start" && "${thisos}" == "Linux" ]]; then
        (
            flock 99
            eval $xcmd
            STATUS=$?
            rm -f $DAFS_LOCK
        ) 99>$DAFS_LOCK
    else
        eval $xcmd
        STATUS=$?
    fi
done
exit ${STATUS}

