#!/bin/bash
#
# groupmon      Script to start and stop the Onappstore control daemon.
#
# Author:       Julian Chesterfield <julian@onapp.com>
#
# chkconfig: 35 99 00
# description: Starts and stops the Onappstore control daemon.

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

MONPID_FILE=/var/run/groupmon.pid
RESTPID=/var/run/nodecontroller.pid
VDISKS_PID=/var/run/rspamd-vdisks
NODES_PID=/var/run/rspamd-nodes
LOCKFILE=/var/lock/subsys/groupmon
MONPROG=groupmon
NODEINITPROG=initSAN
NODESTOPPROG=stopSAN
RESTPROG=nodecontroller
GROUPMON=/usr/bin/groupmon
ONAPPSTORECONF=/etc/onappstore.conf
CHANNEL=`cat $ONAPPSTORECONF | grep ^channel | cut -d'=' -f2`

stop()
{
    dmsetup remove_all -f
    for i in `ls -1 /dev/nbd*`; do bdevclient -d $i &> /dev/null; done
    modprobe -r nbd

    rm -Rf /dev/onapp-*

    echo -n "Stopping program $NODESTOPPROG"
    $NODESTOPPROG
    if [ $? -eq 0 ]; then echo_success; else echo_failure; fi

    echo
    echo -n "Stopping program $MONPROG"
    $GROUPMON -t
    if [ $? -eq 0 ]; then echo_success; else echo_failure; fi

    echo
    echo -n "Stopping program $RESTPROG"
    kill `cat $RESTPID`
    if [ $? -eq 0 ]; then echo_success; else echo_failure; fi

    echo
    echo -n "Stopping vdisk DBs"
    if [ -e $VDISKS_PID ]; then kill `cat $VDISKS_PID`; fi
    if [ $? -eq 0 ]; then echo_success; else echo_failure; fi

    echo
    echo -n "Stopping node DBs"
    if [ -e $NODES_PID ]; then kill `cat $NODES_PID`; fi
    if [ $? -eq 0 ]; then echo_success; else echo_failure; fi

    sleep 1
    rm -f /DB/nodes.db /DB/vdisks.db $LOCKFILE
}

start()
{
    modprobe nbd nbds_max=64
    for i in `seq 0 63`; do echo deadline > /sys/block/nbd${i}/queue/scheduler; done

    if [ -f $LOCKFILE ]; then 
        echo -e "OnappstoreSAN already running (lockfile exists)"
        return; 
    fi

    echo -n "Starting program $NODEINITPROG"
    $NODEINITPROG
    if [ $? -eq 0 ]; then echo_success; else echo_failure; fi

    sleep 2
    echo
    echo -n "Starting program $MONPROG"
    $GROUPMON -i onappstoresan -F -c $CHANNEL
    if [ $? -eq 0 ]; then echo_success; else echo_failure; fi

    echo
    echo -n "Starting program $RESTPROG"
    $RESTPROG
    if [ $? -eq 0 ]; then echo_success; else echo_failure; fi
    touch $LOCKFILE
}

case "$1" in
    start)
    start
    ;;
    stop)
    stop
    ;;
    restart)
    stop
    start
    ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
	;;
esac

echo
