#!/bin/bash

# Copyright (C) 2011 NTT DATA Corporation
#
# This program is free software; you can redistribute it and/or
# Modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details

SCRIPT_DIR=$(cd $(dirname $0);pwd)
. ${SCRIPT_DIR}/../conf/hinemos_agent.cfg
TIMEOUT=5
export PROG=`basename $0`

# Logging
function Logging() {
    MODE=$2
    OPTS="-e"
    case ${MODE} in
        withline)
            EchoLine
            Logging "$1"
            EchoLine
            return 0
            ;;
        noreturn)
            OPTS="${OPTS} -n"
            ;;
        *)
            ;;
    esac
    echo ${OPTS} "$1" >&2
    /usr/bin/logger "${PROG} $1"
}

# shutdown process
if [ -f ${HINEMOS_AGENT_PID} ]
then
        read PID < ${HINEMOS_AGENT_PID}
        if [ `ps --no-headers --pid ${PID} e | grep "java.*com.clustercontrol.agent.Agent" | wc -l` -gt 0 ]
        then
                # shutdown (send TERM signal)
                kill ${PID}
        fi
else
        Logging "Hinemos Agent is not running."
        exit 1
fi

## check process
for TIME in `seq 1 ${TIMEOUT}`
do
        if [ `ps --no-headers --pid ${PID} e | grep "java.*com.clustercontrol.agent.Agent" | wc -l` -eq 0 ]
        then
                Logging "Hinemos Agent stopped."
                rm -f ${HINEMOS_AGENT_PID}
                exit 0
        fi
        sleep 1
done

Logging "Hinemos Agent shutdown failed."
exit 1
