#!/bin/sh
#
# Simple Redis init.d script conceived to work on Linux systems
# as it does use of the /proc filesystem.
#
# description: Redis is an in memory key-value store database
#
### BEGIN INIT INFO
# Provides: redissentinel_<%=@name%>
# Required-Start:
# Required-Stop:
# Should-Start:
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description:
# Description: redissentinel_<%=@name%> init script
### END INIT INFO

SENTINELNAME=<%= @name %>
<% case @platform %>
<% when 'ubuntu','debian','fedora' %>
EXEC="su -s /bin/sh -c '<%= File.join(@bin_path, 'redis-server') %> <%= @configdir %>/${SENTINELNAME}.conf --sentinel' <%= @user %>"
<% else %>
EXEC="runuser <%= @user %> -c \"<%= File.join(@bin_path, 'redis-server') %> <%= @configdir %>/${SENTINELNAME}.conf --sentinel\""
<% end %>
CLIEXEC=<%= File.join(@bin_path, 'redis-cli') %>


PIDFILE=<%= @piddir %>/${SENTINELNAME}.pid

if [ ! -d <%= @piddir %> ]; then
    mkdir -p <%= @piddir %>
    chown <%= @user %>  <%= @piddir %>
fi

case "$1" in
    status)
        if [ -f $PIDFILE ]
        then
          echo "redis$SENTINELNAME $PIDFILE exists, pid is $(cat $PIDFILE), should be running"
          ps -p $(cat $PIDFILE) >/dev/null 2>&1
          exit $?
        else
          echo "redis$SENTINELNAME $PIDFILE doesn't exist"
          exit 3
        fi
        ;;
    start)
        if [ -f $PIDFILE ]
        then
                echo "$PIDFILE exists, process is already running or crashed"
        else
                echo "Starting Redis server..."
                eval $EXEC
        fi
        ;;
    stop)
        if [ ! -f $PIDFILE ]
        then
                echo "$PIDFILE does not exist, process is not running"
        else
                PID=$(cat $PIDFILE)
                echo "Stopping ..."

                kill ${PID}

                while [ -x /proc/${PID} ]
                do
                    echo "Waiting for Redis to shutdown ..."
                    sleep 1
                done
                echo "Redis stopped"
        fi
        ;;
    *)
        echo "Please use start or stop as first argument"
        ;;
esac
