#!/bin/sh
#
# haproxy	This shell script takes care of starting and stopping
#		haproxy.
#
# chkconfig:	345 80 30
#
# description:	haproxy - high-performance TCP/HTTP load balancer
#
# processname:	haproxy
# pidfile:	/var/run/haproxy.pid
# config:	/etc/haproxy/haproxy.cfg

# 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

checkconfig() {
	/usr/sbin/haproxy -q -c -f /etc/haproxy/haproxy.cfg || exit 1
}

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 /var/run/haproxy.pid
	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 /var/run/haproxy.pid haproxy
	rm -f /var/lock/subsys/haproxy
}

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

	# TODO: check if pid is valid and start instead
	checkconfig
	msg_reloading "HA-Proxy"
	daemon /usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -p /var/run/haproxy.pid -st $(</var/run/haproxy.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
