#!/bin/sh

# This file is part of asterisk-phonepatch

# Copyright (C) 2006 Arnau Sanchez
#
# Asterisk-phonepatch is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License or any later version.

DAEMON="/usr/sbin/asterisk-phonepatch"
CONF="/etc/asterisk-phonepatch.conf"
DAEMON_OPTIONS="--background"
DAEMON_NAME="Asterisk Phonepatch daemons"

###########################
read_conf() 
{
	TEMP=$(tempfile)
	PHP_CONF=$(cat $CONF | grep -v "^[[:space:]]*#" | tee $TEMP)

	if [ "$PHP_CONF" = "" ]; then 
		echo "No daemons enabled: configure $CONF"
		rm -f $TEMP
		exit 0
	fi
}

test -f $DAEMON || exit 0

if [ ! -e $CONF ]; then echo "main configuration file not found: $CONF"; exit 1; fi

##########
#############
case "$1" in

#############
start)
	read_conf
	echo "Starting $DAEMON_NAME:"
	while read LINE; do 
		NAME=$(echo $LINE | awk '{print $1}')
		FILE=$(echo $LINE | awk '{print $2}')
		if [ "$NAME" = "" -o "$FILE" = "" ]; then 
			echo "syntax error: $LINE"
			continue
		fi
		echo -n " $NAME: "
		if [ ! -e $FILE ]; then echo "file not found ($FILE)";  continue; fi
		if $DAEMON --configuration-file $FILE $DAEMON_OPTIONS;  then echo "done"
		else echo "failed"; fi
	done < $TEMP
	rm -f $TEMP
	;;

#############
stop)
	read_conf

	echo "Stopping $DAEMON_NAME:"
	
	while read LINE; do 
		NAME=$(echo $LINE | awk '{print $1}')
		FILE=$(echo $LINE | awk '{print $2}')
		if [ "$NAME" = "" -o "$FILE" = "" ]; then 
			echo "syntax error: $LINE"
			continue
		fi
		echo -n " $NAME: "
		if [ ! -e $FILE ]; then echo "file not found ($FILE)"; continue; fi
		PIDFILE=$(cat $FILE | grep "^[[:space:]]*pidfile[[:space:]]*=" | head -n1 | cut -d"=" -f2 | tr -d "\"'" | xargs)
		if [ "$PIDFILE" = "" ]; then echo "pidfile not configured ($FILE)"; continue; fi
		PID=$(cat $PIDFILE 2>/dev/null)
		if [ "$PID" = "" ]; then echo "not found"
		else
			kill $PID &>/dev/null
			if [ $? -eq 0 ]; then echo "done"
			else echo "kill error"; fi
		fi
		rm -f $PIDFILE
	done < $TEMP
	rm -f $TEMP
	;;
	
#############
restart|force-reload)
	$0 stop
	$0 start
	;;

#############
*)
	echo "usage: $(basename $0) start|stop|restart|force-reload"
	exit 1
	;;
esac

exit 0
