#!/bin/bash
#
# storageAPI - this script starts and stops the storageAPI daemon
#
# chkconfig:   - 85 15 
# description:  storageAPI provides a REST API for storage operations
# processname: python
# pidfile:     /var/run/storageAPI.pid

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Source Onapp vars
if [ -e /etc/onapp.conf ]; then
    . /etc/onapp.conf
fi

# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0

APIutil="/usr/pythoncontroller/storageAPI.py"
pythonBIN="/usr/pythoncontroller/python3"
prog=$(basename $APIutil)

lockfile=/var/lock/subsys/cputils

start() {
    [ -x $APIutil ] || exit 5
    echo -n $"Starting $prog: "
    ARGS=""
    if [ ! -z $HOST ]; then ARGS="-s $HOST"; fi
    $APIutil $ARGS
    touch $lockfile
    return 0
}

stop() {
    echo -n $"Stopping $prog: "
    pkill -f storageAPI.py
    rm -f $lockfile
    return 0
}

restart() {
    stop
    start
}

rh_status_q() {
    result=0
    local result_str=$(pgrep -f storageAPI.py | wc -l)
    if [[ $result_str == "0" ]] ; then
        result=1
    else
        result=0
    fi
    return $result
}

rh_status() {
    rh_status_q
    if [[ $result == 1 ]] ; then
        echo "Stoped: $prog"
    else
        echo "Started: $(pgrep -fl storageAPI.py)"
    fi
    return $(( !$result ))
}

case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart)
        $1
        ;;
    status)
        rh_status
        ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart}"
        exit 2
esac
