#!/bin/bash
# chkconfig: 2345 25 75
# description: Data Safe Restore Client
### BEGIN INIT INFO
# Provides:             dsr
# Required-Start:       $local_fs $network
# Required-Stop:        $local_fs
# Default-Start:        2 3 4 5
# Default-Stop:         0 1 6
# Short-Description:    Start dsr daemon at boot time
# Description:          Data Safe Restore Client
### END INIT INFO

DSRDIR=/usr/local/dsr
DSR=$DSRDIR/dsr
PIDFILE="$DSRDIR/conf/pid"
PID=""
RUNNING=0

check_running()
{
	RUNNING=0
	if [ -f $PIDFILE ]; then
		PID=$(cat $PIDFILE)
		IS_RUNNING=`ps u -p $PID | grep $DSR | grep -v grep`
		if [ ! -z "$IS_RUNNING" ]; then
			RUNNING=1
		fi
	fi
}

wait_running()
{
	check_running

	if [ "$1" -eq "$RUNNING" ]; then
		echo "done."
		return
	fi

	WAIT=0
	while [[ "$WAIT" -lt 20 && "$1" -ne "$RUNNING" ]]; do
		WAIT=$(expr $WAIT + 1)
		sleep 1
		check_running
	done

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

dsr_start()
{
	echo -n "Starting Data Safe Restore: "
	check_running
	if [ "$RUNNING" -eq 1 ]; then
		echo "Already Running"
	else
		nohup $DSR &> /dev/null &
		wait_running 1
	fi
}

dsr_stop()
{
	echo -n "Stopping Data Safe Restore: "
	check_running
	if [ "$RUNNING" -eq 0 ]; then
		echo "Not Running"
	else
		kill $PID
		wait_running 0
	fi
}

case "$1" in
	start)
		dsr_start
		;;
	stop)
		dsr_stop
		;;
	restart)
		dsr_stop
		dsr_start
		;;
	status)
		check_running
		if [ "$RUNNING" -eq 1 ]; then
			echo "DSR is Running with pid $PID"
		else
			echo "DSR is not running"
		fi
		;;
	*)
		echo "Usage: /etc/init.d/dsr {start|stop|restart|status}"
		;;
esac
