# -*-Shell-script-*-
#
# functions	This file contains functions to be used by most or all
#		shell scripts in the /etc/sdk directory.
#

# Check if any of $pid (could be plural) are running
checkpid() {
	local i

	for i in $* ; do
		[ -d "/proc/$i" ] && return 0
	done
	return 1
}

# Set $pid to pids from /var/run* for {program}.  $pid should be declared
# local in the caller.
# Returns LSB exit code for the 'status' action.
__pids_var_run() {
	local base=${1##*/}
	local pid_file=${2:-/var/run/$base.pid}

	pid=
	if [ -f "$pid_file" ] ; then
	        local line p

		[ ! -r "$pid_file" ] && return 4 # "user had insufficient privilege"
		while : ; do
			read line
			[ -z "$line" ] && break
			for p in $line ; do
				[ -z "${p//[0-9]/}" -a -d "/proc/$p" ] && pid="$pid $p"
			done
		done < "$pid_file"

	        if [ -n "$pid" ]; then
	                return 0
	        fi
		return 1 # "Program is dead and /var/run pid file exists"
	fi
	return 3 # "Program is not running"
}

# Output PIDs of matching processes, found using pidof
__pids_pidof() {
	pidof -o $$ -o $PPID -o %PPID "$1" || \
		pidof -o $$ -o $PPID -o %PPID "${1##*/}"
}

status() {
	local base pid pid_file=

	# Test syntax.
	if [ "$#" = 0 ] ; then
		echo "Usage: status [-p pidfile] {program}"
		return 1
	fi
	if [ "$1" = "-p" ]; then
		pid_file=$2
		shift 2
	fi	
	base=${1##*/}

	# First try "pidof"
	__pids_var_run "$1" "$pid_file"
	RC=$?
	if [ -z "$pid_file" -a -z "$pid" ]; then
		pid="$(__pids_pidof "$1")"
	fi
	if [ -n "$pid" ]; then
	        echo "${base} (pid $pid) is running..."
	        return 0
	fi

	case "$RC" in
		0)
			echo "${base} (pid $pid) is running..."
			return 0
			;;
		1)
	                echo "${base} dead but pid file exists"
	                return 1
			;;
		4)
			echo "${base} status unknown due to insufficient privileges."
			return 4
			;;
	esac	
	echo "${base} is stopped"
	return 3
}

# A function to stop a program.
killproc() {
	local RC killlevel= base pid pid_file= delay try

	RC=0; delay=3; try=0
	# Test syntax.
	if [ "$#" -eq 0 ]; then
		echo "Usage: killproc [-p pidfile] [ -d delay] {program} [-signal]"
		return 1
	fi
	if [ "$1" = "-p" ]; then
		pid_file=$2
		shift 2
	fi
	if [ "$1" = "-d" ]; then
		delay=$(echo $2 | awk -v RS=' ' -v IGNORECASE=1 '{if($1!~/^[0-9.]+[smhd]?$/) exit 1;d=$1~/s$|^[0-9.]*$/?1:$1~/m$/?60:$1~/h$/?60*60:$1~/d$/?24*60*60:-1;if(d==-1) exit 1;delay+=d*$1} END {printf("%d",delay+0.5)}')
		if [ "$?" -eq 1 ]; then
			echo "Usage: killproc [-p pidfile] [ -d delay] {program} [-signal]"
			return 1
		fi
		shift 2
	fi
        

	# check for second arg to be kill level
	[ -n "${2:-}" ] && killlevel=$2

        # Save basename.
        base=${1##*/}

        # Find pid.
	__pids_var_run "$1" "$pid_file"
	RC=$?
	if [ -z "$pid" ]; then
		if [ -z "$pid_file" ]; then
			pid="$(__pids_pidof "$1")"
		else
			[ "$RC" = "4" ] && { echo failed to shutdown $base ; return $RC ;}
		fi
	fi

        # Kill it.
        if [ -n "$pid" ] ; then
		if [ -z "$killlevel" ] ; then
		       if checkpid $pid 2>&1; then
			   # TERM first, then KILL if not dead
			   kill -TERM $pid >/dev/null 2>&1
			   busybox usleep 100000
			   if checkpid $pid ; then
				try=0
				while [ $try -lt $delay ] ; do
					checkpid $pid || break
					sleep 1
					let try+=1
				done
				if checkpid $pid ; then
					kill -KILL $pid >/dev/null 2>&1
					busybox usleep 100000
				fi
			   fi
		        fi
			checkpid $pid
			RC=$?
			[ "$RC" -eq 0 ] && echo failed to shutdown $base
			RC=$((! $RC))
		# use specified level only
		else
		        if checkpid $pid; then
	                	kill $killlevel $pid >/dev/null 2>&1
				RC=$?
				[ "$RC" -eq 0 ] || echo failed to send $killlevel to $base
			elif [ -n "${LSB:-}" ]; then
				RC=7 # Program is not running
			fi
		fi
	else
		if [ -n "${LSB:-}" -a -n "$killlevel" ]; then
			RC=7 # Program is not running
		else
			echo failed to shutdown $base
			RC=0
		fi
	fi

        # Remove pid file if any.
	if [ -z "$killlevel" ]; then
            rm -f "${pid_file:-/var/run/$base.pid}"
	fi
	return $RC
}
