#! /bin/sh
#
# functions	This file contains functions to be used by most or all
#		shell scripts in the /etc/init.d directory.
#
# Version:	@(#) /etc/init.d/functions 1.01 26-Oct-1993
#
# Author:	Miquel van Smoorenburg, <miquels@drinkel.nl.mugnet.org>
# Hacked by:    Greg Galloway and Marc Ewing
#

# First set up a default search path.
export PATH="/sbin:/usr/sbin:/bin:/usr/bin"

# A function to start a program.
daemon() {
	# Test syntax.
	if [ $# = 0 ]; then
		echo "Usage: daemon {program}"
		return 1
	fi

        # Save basename.
        base=`basename $1`

        # See if it's already running.
        [ "`pidofproc $base`" != "" ] && return

	# echo basename of the program.
	echo -n "$base "

	# And start it up.
	$*
}

# A function to stop a program.
killproc() {
	# Test syntax.
	if [ $# = 0 ]; then
		echo "Usage: killproc {program}"
		return 1
	fi

        # Save basename.
        base=`basename $1`

        # Find pid.
        pid=`pidofproc $base`

        # Kill it.
        if [ "$pid" != "" ] ; then
                echo -n "$base "
                kill -9 $pid
	fi

        # Remove pid file if any.
        rm -f /var/run/$base.pid
}

# A function to find the pid of a program.
pidofproc() {
	# Test syntax.
	if [ $# = 0 ] ; then
		echo "Usage: pidofproc {program}"
		return 1
	fi

	# First try "pidof"
	pid=`pidof $1`
	if [ "$pid" != "" ] ; then
	        echo $pid
	        return 0
	fi

	# Next try "/var/run/*.pid" files
	if [ -f /var/run/$1.pid ] ; then
	        pid=`head -1 /var/run/$1.pid`
	        if [ "$pid" != "" ] ; then
	                echo $pid
	                return 0
	        fi
	fi

	# Finally try to extract it from ps
	ps auxw | awk 'BEGIN { prog=ARGV[1]; ARGC=1 } 
			   { if ((prog == $11) || (("(" prog ")") == $11) ||
			   ((prog ":") == $11)) { print $2 } }' $1
}
