#!/bin/sh
#-----------------------------------------------------------------------------
# /usr/local/bin/faxrcv.sh - start or stop capifaxrcvd            3.1.2
#
# Creation:     11.08.2007  chris
# Last Update:  $Id: faxrcv.sh 11968 2006-09-02 15:37:58Z hh $
#-----------------------------------------------------------------------------

THISSCRIPT=`basename "$0"`
DAEMON="/var/caiviar/capiserver"
DAEMON_DESC="caiviar capiserver"
DAEMON_STOP_FILE="/var/run/capiserver.stop"

. /var/run/caiviar.conf

## usage [error]*
# display usage message and terminates program
usage () {
	case "$#" in
		0) 
		;;
		*) echo "$THISSCRIPT: ERROR $@" 
		;;
	esac
	
	echo
	echo "Usage: $THISSCRIPT start|stop|test|status"
	echo
	echo "Starts or stops $DAEMON_DESC."
	exit 1
}

## start_daemon caiviar capiserver
start_daemon () {
	#if ps | grep capiserver | grep -v grep
	#if is_running
	is_running
	if [ "$?" -eq "1" ]; then
		colecho "$DAEMON_DESC already running, won't start it twice..." br x br
	else
		colecho "starting $DAEMON_DESC..." gn
		#capiserver &
		while [ ! -f $DAEMON_STOP_FILE ] ; do
			#$DAEMON & > /dev/null 2>&1
			$DAEMON
		done &
	fi
}

## start_daemon caiviar capiserver
test_capiserver () {
	#if ps | grep capiserver | grep -v grep
	#if is_running
	is_running
	if [ "$?" -eq "1" ]; then
		colecho "$DAEMON_DESC already running, won't start it twice..." br x br
	else
		colecho "starting $DAEMON_DESC in test-mode..." gn
		colecho "exit with Strg+C" gn
		#capiserver
		$DAEMON
	fi
}

## stop_daemon caiviar capiserver
stop_daemon () {
	echo > $DAEMON_STOP_FILE
	ps | grep capiserver | grep -v grep | while read pid uid vmsize stat command args
	do
		colecho "killing capiserver (PID: $pid) ..." gn
		kill $pid
		sleep 2
		if ps | grep -qe "^\W*$pid"
		then
			colecho "could not kill $DAEMON_DESC (you may want to retry by calling this script again)" br x br
		fi
	done
	sleep 5
	rm $DAEMON_STOP_FILE
}

is_running() {
	if ps | grep capiserver | grep -v grep >> /dev/null
	then
		return 1
	else
		return 0
	fi
}


action="$1"

case "$action" in
	start)
		start_daemon
	;;
	stop)
		stop_daemon
	;;
	status)
		is_running
		if [ "$?" -eq "1" ]; then
			colecho "$DAEMON_DESC is running" gn
		else
			colecho "$DAEMON_DESC is not running" br x br
		fi
	;;
	test)
		test_capiserver
	;;
	help|--help|-h)
		usage
	;;
	*)
		usage "unknown parameter"
	;;
esac