#!/bin/sh
#
# memcached		memcached
#
# chkconfig:	345 60 40
#
# description:	memcached is a cache daemon.
#
# processname:	memcached
# pidfile:      /var/run/memcached.pid
#

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

# Get network config
. /etc/sysconfig/network

MEMUSAGE="64"
MEMCACHED_RUNAS="memcached"
MAXCONN="1024"
LISTEN="127.0.0.1:11211"

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

if [ "$LISTENON" -a "$PORT" ]; then
	# backward compat config
	LISTEN="$LISTENON:$PORT"
fi

start() {
	# Check if the service is already running?
	if [ -f /var/lock/subsys/memcached ]; then
		msg_already_running "memcached"
		return
	fi

	local listen ip port ret=0
	for listen in $LISTEN; do
		ip=${listen%:*}
		port=${listen##*:}
		msg_starting "memcached ($ip:$port)"
		pidfile=/var/run/memcached/"$ip.$port.pid"
		daemon --pidfile $pidfile --user $MEMCACHED_RUNAS \
			/usr/sbin/memcached -d -P $pidfile -l $ip -p $port \
			-m $MEMUSAGE -c $MAXCONN -u $MEMCACHED_RUNAS $MEMCACHED_OPTS
		ret=$?
		[ $ret = 0 ] || RETVAL=$?
	done
	[ $RETVAL -eq 0 ] && touch /var/lock/subsys/memcached
}

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

	local listen ip port
	for listen in $LISTEN; do
		ip=${listen%:*}
		port=${listen##*:}
		msg_stopping "memcached ($ip:$port)"
		pidfile=/var/run/memcached/"$ip.$port.pid"
		killproc --pidfile $pidfile memcached
	done
	rm -f /var/lock/subsys/memcached >/dev/null 2>&1
}

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

	stop
	start
}

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

	local listen ip port
	for listen in $LISTEN; do
		ip=${listen%:*}
		port=${listen##*:}
		msg_reloading "memcached ($ip:$port)"
		pidfile=/var/run/memcached/"$ip.$port.pid"
		killproc --pidfile $pidfile memcached -HUP
		RETVAL=$((RETVAL + $?))
	done
}

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

exit $RETVAL
