#!/bin/bash
#
# ccsd   start/stop ccsd
#
# chkconfig: 345 20 80
# description: Starts and stops the ccsd specified by $CCS_ARCHIVE \
#              in /etc/sysconfig/gfs
#
#	       
### BEGIN INIT INFO
# Provides: 
### END INIT INFO

. /etc/init.d/functions
[ -f /etc/sysconfig/gfs ] && . /etc/sysconfig/gfs

# attempt to autodetect a CCA device.  If a single CCA device is found
# CCS_ARCHIVE will be set to that device and return 0.  If more than
# one device is found, autodetect() will not set CCS_ARCHIVE and will 
# return 1
# XXX: Should this also scan for cca files in /etc/sysconfig?
autodetect()
{
	ccadevs=$( pool_tool -s | awk '/CCA device /{print $1}' | xargs -r )
	[ -z "$ccadevs" ] && return 1

	match=""
	for dev in $ccadevs
	do
		if [ -z "$match" ]
		then
			match=$dev
		else
			return 1
		fi
	done

	CCS_ARCHIVE=$match
	return 0
}


get_clustername()
{
	clustername=$(ccs_read string cluster.ccs cluster/name 2>/dev/null)
}

start()
{
	echo -n "Starting ccsd:"
	# verify that CCS_ARCHIVE is defineddd
	if [ -z "$CCS_ARCHIVE" ]
	then
		if ! autodetect 
		then
			echo "CCS_ARCHIVE not specified in /etc/sysconfig/gfs" >&2
			return 1
		fi
	fi

	# determine if ccsd needs the '-f' '-d' or '-s' option
	if [ -b "$CCS_ARCHIVE" ]
	then
		ccs_type="-d"
	elif [ -f "$CCS_ARCHIVE" ]
	then
		ccs_type="-f"
	else
		ccs_type="-s"
	fi	

	# start ccsd
	if ccsd $ccs_type $CCS_ARCHIVE &>/dev/null
	then

		# verify that ccsd has infact started
		for sec in $(seq 1 10) 
		do
			sleep 1 
			if get_clustername
			then
				echo -n " clustername = $clustername"
				success "startup"
				echo 
				return 0
			fi
		done
	fi

	failure "startup"
	echo
	return 1
}

stop()
{
	echo -n "Stopping ccsd:"
	for sec in $(seq 1 10) 
	do
		if get_clustername
		then
			# get the pid of ccsd from /var/run/sistina/ccsd.pid
			# and break if the file is not there
			[ -r /var/run/sistina/ccsd.pid ] || break

			pid=$(cat /var/run/sistina/ccsd.pid )
			kill $pid
			
			sleep 1 
		else
			success "shutdown"
			echo
			return 0
		fi
	done
	failure "shutdown"
	echo
	return 1
}

rtrn=1

# See how we were called.
case "$1" in
  start)
	start
	rtrn=$?
	[ $rtrn = 0 ] && touch /var/lock/subsys/ccsd
	;;

  stop)
	stop
	rtrn=$?
	[ $rtrn = 0 ] && rm -f /var/lock/subsys/ccsd
	;;

  restart)
	$0 stop
	$0 start 
	rtrn=$?
	;;

  status)
	status ccsd
	rtrn=0
	;;

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

exit $rtrn
