# -*-Shell-script-*-
#
# functions	This file contains functions to be used by most or all
#		shell scripts in the /etc/init.d directory.
#
# Written by T.Nonogaki @Stray Penguin

TEXTDOMAIN=initscripts

unset -f pidfileofproc pidofproc status

# A function to find the pid of a program. Looks *only* at the pidfile
pidfileofproc() {
	local base=${1##*/}
	local pidfile=/var/spool/$(basename $0)/pid/master.pid
	
	# Test syntax.
	if [ "$#" = 0 ] ; then
		echo $"Usage: pidfileofproc {program}"
		return 1
	fi

	# First try "/var/spool/postfix[-deux]/pid/master.pid" file
	if [ -f $pidfile ] ; then
	        local line p pid=
		read line < $pidfile
		for p in $line ; do
		       [ -z "${p//[0-9]/}" -a -d /proc/$p ] && pid="$pid $p"
		done
	        if [ -n "$pid" ]; then
	                echo $pid
	                return 0
	        fi
	fi
}

# A function to find the pid of a program.
pidofproc() {
	base=${1##*/}
	local pidfile=/var/spool/$(basename $0)/pid/master.pid

	# Test syntax.
	if [ "$#" = 0 ]; then
		echo $"Usage: pidofproc {program}"
		return 1
	fi

	# First try "/var/spool/postfix[-deux]/pid/master.pid" file
	if [ -f $pidfile ]; then
	        local line p pid=
		read line < $pidfile
		for p in $line ; do
		       [ -z "${p//[0-9]/}" -a -d /proc/$p ] && pid="$pid $p"
		done
	        if [ -n "$pid" ]; then
	                echo $pid
	                return 0
	        fi
	fi
	pidof -o $$ -o $PPID -o %PPID -x $1 || \
		pidof -o $$ -o $PPID -o %PPID -x $base
}

status() {
	local base=${1##*/}
	local pid fpid i
	local pidfile=/var/spool/$(basename $0)/pid/master.pid

	# Test syntax.
	if [ "$#" = 0 ] ; then
		echo $"Usage: status {program}"
		return 1
	fi

	# Examin "/var/spool/postfix[-deux]/pid/master.pid" file
	if [ -f $pidfile ] ; then
	        read pid < $pidfile
	        [ -n "$pid" ] && fpid=$pid
	fi

	# Then, first try "pidof"
	pid=`pidof -o $$ -o $PPID -o %PPID -x $1 || \
	     pidof -o $$ -o $PPID -o %PPID -x ${base}`
	for i in ${pid[@]}; do
	        if [ "$i" = "$fpid" ]; then
	                unset pid
	                pid=$fpid
	                break
	        fi
	done

	if [ -n "$pid" ]; then
	        echo $"${base} (pid $pid) is running..."
	        return 0
	fi

	# Next try "/var/spool/postfix[-deux]/pid/master.pid" file
	if [ -f $pidfile ] ; then
	        read pid < $pidfile
	        if [ -n "$pid" ]; then
	                echo $"${base} dead but pid file exists"
	                return 1
	        fi
	fi
	# See if /var/lock/subsys/postfix[-deux] exists
	if [ -f /var/lock/subsys/$(basename $0) ]; then
		echo $"${base} dead but subsys locked"
		return 2
	fi
	echo $"${base} is stopped"
	return 3
}
