#!/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
PID_NAME="${PID_DIR}/$(basename $PWD).pid"
source ${INSTALL_DIR}/etc/init.d/hpcc_common

component=$(basename $PWD)
dir.getByName lock
lock="$dir_return"
export logfile="${LOG_DIR}/${component}/init_${component}_$(date +%Y_%m_%d_%H_%M_%S).log"

export SENTINEL="esp.sentinel"
log "Removing $SENTINEL"
rm -f ${SENTINEL}

SNMPID=$$

killed()
{
    kill_process ${PID_NAME} esp 15 ${SENTINEL}
    if [[ $? -eq 1 ]]; then
        log "could not kill $component"
    else
        log "$component Stopped"
        unlock ${LOCK_DIR}/$component/${component}.lock
    fi
    exit 255
}

trap "killed" SIGINT SIGTERM SIGKILL
log "Calling esp snmpid=$SNMPID 1>/dev/null 2>/dev/null &"
esp snmpid=$SNMPID 1>/dev/null 2>/dev/null &
echo $! > $PID_NAME
wait
log "Removing $PID_NAME"
rm $PID_NAME
while [[ -e ${SENTINEL} ]]; do
    sleep 5
    if [[ -e ${SENTINEL} ]]; then
        log "Calling esp snmpid=$SNMPID 1>/dev/null 2>/dev/null &"
        esp snmpid=$SNMPID 1>/dev/null 2>/dev/null &
        echo $! > $PID_NAME
        wait
        log "Removing $PID_NAME"
        rm $PID_NAME
    fi
done
