#
# Copyright (c) 2010 NetApp, Inc., All Rights Reserved
#

PACKAGE=/opt/NetApp/snapdrive
. $PACKAGE/snapdrived_var.rcscript

RETVAL=0
# If system is rebooting/shutting down, dont remove cron job
rlevel=`$WHO -r | $AWK '{ print $2 }'`
if [ $rlevel -eq 0 -o $rlevel -eq 6 ] ; then
	exit $RETVAL
fi
# Removing the cron job from list so that it is not executed again 
$CRONTAB -l 2>&1 | $GREP "snapdrived_cron" 1>/dev/null 2>&1 
if [ $? -eq 0 ] ; then
	$CRONTAB -l | $GREP -v "snapdrived_cron" > $TMPCRONFILE
	if [ ! -s $TMPCRONFILE ] ; then
		$CRONTAB -r
		RETVAL=$?
	else
		$CRONTAB $TMPCRONFILE 1>/dev/null 2>&1 
		RETVAL=$?
	fi
	if [ $RETVAL -ne 0 ] ; then
		echo "Failed to remove SnapDrive Daemon start cron job. Please remove it manually."
		RETVAL=1
	fi
	$RM -f $TMPCRONFILE
fi
rlevel=`$WHO -r | $AWK '{ print $2 }'`
if [ $rlevel -le 1 ] ; then
    echo "Snapdrive Daemon is recommended to start at multi-user mode."
	echo "Snapdrive Daemon start FAILED. Please restart it manually."
	touch $LOCKFILE
	exit 1;
fi
# Sleep for $SLEEP_TIME_IN_SEC seconds before starting the SnapDrive Daemon.
# We sleep to make sure the dependents services are up and initialized before
# SnapDrive Daemon initializes.
sleep $SLEEP_TIME_IN_SEC
$PS -ef | $GREP "snapdrived[\ ]*[re]*start" | $GREP -v "grep"
if [ $? -ne 0 ] ; then
	$SNAPDRIVED start
	if [ $? -eq 0 ] ; then
		echo "Snapdrive Daemon started SUCCESSFULLY."
	else
    	echo "Snapdrive Daemon start FAILED. Please restart it manually."
	fi
else
	echo "SnapDrive Daemon already running."
fi
touch $LOCKFILE
