#!/bin/sh
#chkconfig: 2345 99 99
### BEGIN INIT INFO
# Provides: hwprepsysagent
# Required-Start: $remote_fs $syslog
# Required-Stop:  $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start daemon at boot time
# Description: This is Huawei HDA prepsysagent service.
### END INIT INFO
#description:auto_run
#
# Service module init script for SLE.
#
# Register service module to init.d with the following command:
# $ insserv /etc/rc.d/module
#

### BEGIN INIT INFO
# Provides: hwprepnetservice
# Required-Start:
# Required-Stop:
# Default-start:
# Default-Stop:
# Short-Description: Excute HUAWEI hwprepnetservice manager
# Description:
### END INIT INFO

#. /etc/rc.status

MODULE_NAME=hwprepnetservice20

MODULE_BINARY=/usr/local/hdpserver/hwsysagent/${MODULE_NAME}
MODULE_SERVICE=/lib/systemd/system/hwprepnet_monitor20.service
OLD_HDP_LOG_SCRIPT=/usr/local/hdpserver/scripts/hdplogservice
HDP_LOG_SCRIPT=/usr/huawei/hdpserver/scripts/hdplogservice

OS_NAME="ubuntu"
if [ -f /etc/os-release ]; then
    OS_NAME=$(cat /etc/os-release |grep ^ID= |awk -F= '{print $2}'|sed 's/\"//g')
elif [ -f /etc/system-release ]; then
    OS_NAME=$(cat /etc/system-release | sed -n '1p')
fi

if [ "$OS_NAME" = "centos" ]; then
    MODULE_SERVICE=/usr/lib/systemd/system/hwprepnet_monitor20.service
fi 

start()
{
    if [ -f $OLD_HDP_LOG_SCRIPT ]; then
        /bin/bash -c "$OLD_HDP_LOG_SCRIPT wait"
    else
        /bin/bash -c "$HDP_LOG_SCRIPT wait"
    fi
    if ! check_status $MODULE_BINARY; then
        echo "Starting the \"$MODULE_NAME\""
        # call the binary file.
        export LD_LIBRARY_PATH=/usr/local/hdpserver/hwsysagent/lib64
        $MODULE_BINARY
        if [ $? -ne 0 ]; then
            echo_failure
            exit 1
        fi
    fi

    sleep 1
    echo_success
	
    if [ -f $MODULE_SERVICE ]; then
        while check_status $MODULE_BINARY; do sleep 1; done
    fi
}

stop()
{
    echo "Shutting down \"$MODULE_NAME\""

    pkill -TERM -f $MODULE_BINARY

    sleep 1
    if check_status $MODULE_BINARY; then
        sleep 1
        pkill -KILL -f $MODULE_BINARY
    fi

    echo_success
}

restart()
{
    stop
    sleep 1
    start
}

usages()
{
    echo "usage : $0 start|stop|restart"
}

check_status()
{
    ps ax | grep -v grep | grep $1 > /dev/null
}

echo_success()
{
    true
}

echo_failure()
{
    false
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    *)
        usages
        exit 1
esac

exit 0
