#!/bin/sh
#
# description: HA-Proxy is a TCP/HTTP reverse proxy which is particularly suited \
#              for high availability environments.
# chkconfig:	345 80 30
# description:	haproxy - high-performance TCP/HTTP load balancer
# processname:	haproxy
# config:	/etc/haproxy/haproxy.cfg
# pidfile:	/var/run/haproxy.pid

# Source function library
. /etc/rc.d/init.d/functions

# Get network config
. /etc/sysconfig/network

# Get service config
[ -f /etc/sysconfig/haproxy ] && . /etc/sysconfig/haproxy

# Check that networking is up.
if is_yes "${NETWORKING}"; then
	if [ ! -f /var/lock/subsys/network -a "$1" != stop -a "$1" != status ]; then
		msg_network_down "HA-Proxy"
		exit 1
	fi
else
	exit 0
fi

pidfile="/var/run/haproxy.pid"

# configtest itself
# must return non-zero if check failed
# output is discarded if checkconfig is ran without details
configtest() {
	/usr/sbin/haproxy -q -c -f /etc/haproxy/haproxy.cfg
	return $?
}

# wrapper for configtest
checkconfig() {
	local details=${1:-0}

	if [ $details = 1 ]; then
		# run config test and display report (status action)
		show "Checking %s configuration" "HA-Proxy"; busy
		local out
		out=$(configtest 2>&1)
		RETVAL=$?
		if [ $RETVAL = 0 ]; then
			ok
		else
			fail
		fi
		[ "$out" ] && echo >&2 "$out"
	else
		# run config test and abort with nice message if failed
		# (for actions checking status before action).
		configtest >/dev/null 2>&1
		RETVAL=$?
		if [ $RETVAL != 0 ]; then
			show "Checking %s configuration" "HA-Proxy"; fail
			nls 'Configuration test failed. See details with %s "checkconfig"' $0
			exit $RETVAL
		fi
	fi
}

start() {
	if [ -f /var/lock/subsys/haproxy ]; then
		msg_already_running "HA-Proxy"
		return
	fi

	msg_starting "HA-Proxy"
	daemon /usr/sbin/haproxy -D -f /etc/haproxy/haproxy.cfg -p $pidfile
	RETVAL=$?
	[ $RETVAL -eq 0 ] && touch /var/lock/subsys/haproxy
}

stop() {
	if [ ! -f /var/lock/subsys/haproxy ]; then
		msg_not_running "HA-Proxy"
		return
	fi

	msg_stopping "HA-Proxy"
	killproc --pidfile $pidfile haproxy
	rm -f /var/lock/subsys/haproxy
}

reload() {
	local pid
	if [ ! -f /var/lock/subsys/haproxy ]; then
		msg_not_running "HA-Proxy"
		RETVAL=7
		return
	fi

	checkconfig
	msg_reloading "HA-Proxy"
	pid=$(cat $pidfile)
	daemon /usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -p $pidfile -st $pid
	RETVAL=$?
}

condrestart() {
	if [ ! -f /var/lock/subsys/haproxy ]; then
		msg_not_running "HA-Proxy"
		RETVAL=$1
		return
	fi

	stop
	start
}

RETVAL=0
# See how we were called.
case "$1" in
  start)
  	start
	;;
  stop)
  	stop
	;;
  restart)
	checkconfig
	stop
	start
	;;
  try-restart)
	condrestart 0
	;;
  reload|force-reload)
  	reload
	;;
  status)
	status haproxy
	exit $?
	;;
  *)
	msg_usage "$0 {start|stop|restart|reload|try-restart|force-reload|status}"
	exit 3
esac

exit $RETVAL
