#!/bin/bash

name=$1
action=$2

desc=""
daemon="/usr/sbin/$NAME"
daemon_args=""
pidfile=/var/run/$NAME.pid
verbose="yes"
timeout=60

# conditions other then "process is running"
other_conditions_exist=0

# this is necessary to avoid syntax error when including
# config file
condition() {
	other_conditions_exist=1
}

[ -r /etc/init.conf.d/$name ] && . /etc/init.conf.d/$name

PATH=/sbin:/usr/sbin:/bin:/usr/bin
[ -r /etc/init.code.d/$name ] && . /etc/init.code.d/$name

if [ "$additional_actions" ]; then
	actions="$actions $additional_actions"
fi

p=`echo "$actions" | sed 's/[[:space:]]+/|/g'`
if ! echo "$action" | grep -E "^$p$" >/dev/null; then
	echo "Unsupported action"
	exit 1
fi

# Example function for checking if a codition is satisfied
file_newer() {
	local f1="$1"
	local f2="$2"
	[ -e "$f1" ] && ! [ -e "$f2" ] || [ "$f1" -nt "$f2" ]
}

port_open() {
	local proto="${1%/*}"
	local port="${1#*/}"
	netstat -tunpl | grep -E "^$proto[[:space:]]+[0-9]*[[:space:]]+[0-9]*[[:space:]]+[0-9:.]+:$port[[:space:]]" >/dev/null
}

check_other_conditions() {
	if [ $other_c -eq 1 ]; then
		grep "^condition " /etc/init.conf.d/$name | while read c t o; do
			eval "${t} $o"
		done
	fi
}

do_status() {
	local s=9
	if status_of_proc "$daemon" "$name"; then
		if check_other_conditions; then
			s=0
		else
			s=2
		fi
	else
		s=1
	fi
	return $s
}

wait_for_status() {
	local ts0=`date +%s`
	local ts1=$ts0
	
	while ! do_status && [ $((ts1-ts0)) -lt $timeout]; do
		sleep 1
		ts1=`date +%s`
	done

	# 0 - ready
	# 1 - not running
	# 2 - running but not ready
	# 4 - cannot access pid file
	# 9 - not determined

	do_status # return most current status
}

do_start() {
	# Return
	#   0 if daemon has been started
	#   1 if daemon was already running
	#   2 if daemon could not be started
	start-stop-daemon --start --quiet --pidfile $pidfile --exec $daemon --test > /dev/null \
		|| return 1
	start-stop-daemon --start --quiet --pidfile $pidfile --exec $daemon -- \
		$daemon_args \
		|| return 2

	wait_for_status
}

do_if() {
	local cond="$1"
	if test $cond; then
		shift
		"$@"
	fi
}

log_if_verbose() {
	local type="$1"
	shift
	do_if "$verbose != no" log_${type}_msg "$@"
}

case action in
	start)
		log_if_verbose "daemon" "Starting $desc" "$name"
		do_start
		case "$?" in
			0|1) log_if_verbose end 0 ;;
			2)   log_if_verbose end 1 ;;
		esac
		;;
	stop)
		do_stop
		;;
	status)
		do_status
		;;
esac
