#!/sbin/sh
#
# munin - init script for munin-node on HP-UX
# PB22Gr 20060725

PATH=/sbin:/bin:/usr/sbin:/usr/bin
NAME=munin-node
DAEMON=/usr/bin/$NAME
CONFFILE=/etc/munin/munin-node.conf
RUN_AS=$(awk '$1~/user/{print$2}' $CONFFILE)
PIDFILE=$(awk '$1~/pid/{print$2}' $CONFFILE)
MYCONF=/etc/rc.config.d/muninconf

test -x $DAEMON || exit 1

if [ -f $MYCONF ]; then
    . $MYCONF
    unset MYCONF
else
    echo "Cannot stat $MYCONF"
    exit 1
fi
[[ $START_MUNIN = 1 ]] || exit 2


get_pid() {
    local from=${1:-pidfile} pid
    if [[ $from = pidfile && -f $PIDFILE ]]; then
        pid=$(cat $PIDFILE)
    else
        pid=$(UNIX95= ps -C $(basename $DAEMON) -o pid=)
    fi
    if [[ -n $pid ]] && kill -0 $pid 2>/dev/null; then
        echo $pid
    fi
}

#get_pid;get_pid ptab;exit

status() {
    local rc=${1:-0}
    printf $(basename $DAEMON)
    pid=$(get_pid)
    if [[ -z $pid ]]; then
        echo " is stopped"
    else
        printf " (pid %d) is running...\n" $pid
    fi
    exit $rc
}

down() {
    local pid=$(get_pid)
    if [[ -z $pid ]]; then
        echo "No $(basename $DAEMON) process running"
        exit 1
    fi
    if kill $pid && sleep 5 && ! kill -0 $pid 2>/dev/null; then
        echo "Stopped $(basename $DAEMON)"
    else
        echo "$(basename $DAEMON) didn't catch SIGTERM, sending it SIGKILL"
        kill -9 $pid
    fi
}

up() {
    local pid=$(get_pid)
    [[ -n $pid ]] && status 1
    echo "Starting $(basename $DAEMON) $@"
    $DAEMON $*
    exit $?
}

action=${1:-status}

case $action in
    start)
        shift
        up $*
        ;;
    stop)
        down
        ;;
    status)
        status
        ;;
    restart)
        down
        up
        ;;
    *)
        echo "usage: munin {start [--debug]|stop|restart|status}" >&2
        exit 1
        ;;
esac
