#!/bin/sh
#
# Copyright (c) 2014 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
### BEGIN INIT INFO
# Provides:          patch-alarm-manager
# Required-Start:    $patch
# Required-Stop:     $patch
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Daemon for polling patch status
# Description:       Daemon for polling patch status
### END INIT INFO

DESC="patch-alarm-manager"
DAEMON="/usr/bin/patch-alarm-manager"
RUNDIR="/var/run"
PIDFILE=$RUNDIR/$DESC.pid

start() 
{
    if [ -e $PIDFILE ]; then
        PID=$(cat $PIDFILE)
        PIDDIR=/proc/${PID}
        if [ -n "${PID}" -a -d ${PIDDIR} ]; then
            echo "$DESC already running."
            exit 0
        else
            echo "Removing stale PID file $PIDFILE"
            rm -f $PIDFILE
        fi
    fi

    echo -n "Starting $DESC..."
    mkdir -p $RUNDIR
    start-stop-daemon --start --quiet \
        --pidfile ${PIDFILE} --exec ${DAEMON} start 
    
    #--make-pidfile 

    if [ $? -eq 0 ]; then
        echo "done."
    else
        echo "failed."
        exit 1
    fi
}

stop()
{
    echo -n "Stopping $DESC..."
    start-stop-daemon --stop --quiet --pidfile $PIDFILE
    if [ $? -eq 0 ]; then
        echo "done."
    else
        echo "failed."
    fi
    rm -f $PIDFILE
}

status()
{
    pid=`cat $PIDFILE 2>/dev/null`
    if [ -n "$pid" ]; then
        if ps -p $pid &>/dev/null ; then
            echo "$DESC is running"
            exit 0
        else
            echo "$DESC is not running but has pid file"
            exit 1
        fi
    fi
    echo "$DESC is not running"
    exit 3
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart|force-reload|reload)
        stop
        start
        ;;
    status)
        status
        ;;
    *)
        echo "Usage: $0 {start|stop|force-reload|restart|reload|status}"
        exit 1
        ;;
esac

exit 0
