#! /bin/sh
#
# memcached      This shell script takes care of starting and stopping Memcached
#
# This script based off Atsushi NAGASE's script at https://gist.github.com/ngs/3081846

# chkconfig: - 55 45
### BEGIN INIT INFO
# Provides: <%= @instance %>
# Required-Start: $network $syslog
# Required-Stop: $network $syslog
# Default-Start:       2 3 4 5
# Default-Stop:        0 1 6
# Description:  The memcached daemon is a network memory cache service.
# Processname: memcached
# Short-Description: start and stop memcached instance <%= @instance %>
### END INIT INFO

ulimit -n <%= @ulimit %>

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

# Source LSB function library.
if [ -r /lib/lsb/init-functions ]; then
    . /lib/lsb/init-functions
else
    echo 'Could not find necessary /lib/lsb/init-functions'
    exit 1
fi

RETVAL=0
prog="memcached"

start () {
    echo -n $"Starting $prog: "

    # ensure that /var/run/memcached actually exists
    if [ ! -d /var/run/memcached ]; then
      mkdir /var/run/memcached
    fi

    # ensure that /var/run/memcached has proper permissions
    if [ "`stat -c %U /var/run/memcached`" != "<%= @user %>" ]; then
        chown <%= @user %> /var/run/memcached
    fi

        start_daemon -p /var/run/memcached/memcached_<%= @instance %>.pid <%= @binary_path %> -d \
          -P /var/run/memcached/memcached_<%= @instance %>.pid <%= @cli_options %> >> <%= @log_file %> 2>&1
        RETVAL=$?
        echo
        [ $RETVAL -eq 0 ] && touch <%= @lock_dir %>/memcached
}
stop () {
        echo -n $"Stopping $prog: "
        killproc -p /var/run/memcached/memcached_<%= @instance %>.pid <%= @binary_path %>
        RETVAL=$?
        echo
        if [ $RETVAL -eq 0 ] ; then
            rm -f <%= @lock_dir %>/memcached
            rm -f /var/run/memcached/memcached_<%= @instance %>.pid
        fi
}

restart () {
        stop
        start
}


# See how we were called.
case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  status)
        status memcached
        ;;
  restart|reload|force-reload)
        restart
        ;;
  condrestart)
        [ -f <%= @lock_dir %>/memcached ] && restart || :
        ;;
  *)
        echo $"Usage: $0 {start|stop|status|restart|reload|force-reload|condrestart}"
        exit 1
esac

exit $?
