#!/bin/sh

PATH='/usr/sbin:/usr/bin'
DESC='ubihealthd UBI device PEB scan daemon'
NAME='ubihealthd'
DAEMON="/usr/sbin/$NAME"
DAEMON_ARGS=''
SCRIPTNAME="/etc/init.d/$NAME"

# exit if binary is missing
[ -x "$DAEMON" ] || exit 0

is_running() {
    start-stop-daemon -K --quiet --test --exec $DAEMON
}

do_start() {
    is_running && return 1
    start-stop-daemon -S --quiet --exec $DAEMON -- $DAEMON_ARGS || return 2
}

do_stop() {
    is_running || return 0
    start-stop-daemon -K --quiet --exec $DAEMON
    RETVAL="$?"

    # wait up to 30 seconds until daemon stopped
    for i in $(seq 30)
    do
        sleep 1
        echo -n '.'
        if ! is_running
        then
            break
        fi
    done

    # see if it's still running
    if is_running
    then
        start-stop-daemon -K --quiet --signal KILL --exec $DAEMON

        for i in $(seq 5)
        do
            sleep 1
            echo -n '.'
            if ! is_running
            then
                break
            fi
        done

        if is_running
        then
            return 2
        fi
    fi

    rm -f $PIDFILE
    return "$RETVAL"
}

case "$1" in
    start)
        echo -n "Starting $DESC ..."
        do_start
        case "$?" in
            0|1)    echo " Done." ;;
            2)      echo " Failed." ;;
        esac
        ;;
    stop)
        echo -n "Stopping $DESC ."
        do_stop
        case "$?" in
            0|1)    echo " Done." ;;
            2)      echo " Failed." ;;
        esac
        ;;
    restart)
        echo -n "Restarting $DESC .."
        do_stop
        case "$?" in
            0|1)
                do_start
                case "$?" in
                    0)  echo " Done." ;;
                    1)  echo " Failed." ;; # Old process still running
                    *)  echo " Failed." ;; # Failed to start
                esac
                ;;
            *)
                echo " Failed." # Failed to stop
                ;;
        esac
        ;;
    status)
        if is_running
        then
            echo "$NAME is running"
        else
            echo "$NAME is not running"
        fi
        ;;
    *)
        echo "Usage: $SCRIPTNAME {start|stop|restart|status}" >&2
        exit 3
        ;;
esac

:
