#!/bin/sh
#
# description: startup script for the Redis server
#
# Nov 29, 2010, Michael Perzl (michael@perzl.org)
#

REDIS_BIN="/opt/freeware/sbin/redis-server"

PIDFILE="/var/run/redis/redis.pid"


# define some generic commands
AWK=/usr/bin/awk
CAT=/usr/bin/cat
ECHO=/usr/bin/echo
GREP=/usr/bin/grep
KILL=/usr/bin/kill
MKDIR=/usr/bin/mkdir
PRINTF=/usr/bin/printf
PS=/usr/bin/ps
RM=/usr/bin/rm


# check for missing binaries (stale symlinks should not happen)
test -x ${REDIS_BIN} ||
    {
      $ECHO "${REDIS_BIN} not installed"
      if [ "$1" = "stop" ] ; then
          exit 0
      else
          exit 5
      fi
    }

# check for existence of necessary config file
REDIS_CONFIG="/opt/freeware/etc/redis.conf"
test -r ${REDIS_CONFIG} ||
    {
      $ECHO "${REDIS_CONFIG} does not exist"
      if [ "$1" = "stop" ] ; then
          exit 0
      else
          exit 6
      fi
    }


case "$1" in
    start)
        if [ -r ${PIDFILE} ] ; then
            pid=`$CAT ${PIDFILE}`
            if [ "`$PS -ef | $GREP -v grep | $GREP redis-server | $GREP ${pid} | $AWK '{ print $2 }'`" = "${pid}" ] ; then
                $ECHO "Redis server is already running with PID ${pid}."
                exit 1
            else
                $RM -f ${PIDFILE}
            fi
        fi
        $PRINTF "Starting Redis server... "
        ## start Redis and write PID to file ${PIDFILE}
        $MKDIR -p /var/run/redis
        ${REDIS_BIN} ${REDIS_CONFIG}
        $ECHO "done."
        ;;
    stop)
        ## stop Redis server
        if [ -r ${PIDFILE} ] ; then
            $PRINTF "Shutting down Redis server... "
            $KILL -TERM `$CAT ${PIDFILE}`
            $RM -f ${PIDFILE}
            $ECHO "done."
        else
            $ECHO "Redis server is not running."
        fi
        ;;
    status)
        if [ -r ${PIDFILE} ] ; then
            pid=`$CAT ${PIDFILE}`
            if [ "`$PS -ef | $GREP -v grep | $GREP redis-server | $GREP ${pid} | $AWK '{ print $2 }'`" = "${pid}" ] ; then
                $ECHO "Redis server is running with PID ${pid}."
            fi
        else
            $ECHO "Redis server is not running."
        fi
        ;;
    restart)
        ## Stop the service and regardless of whether it was
        ## running or not, start it again.
        $0 stop
        $0 start
        ;;
    *)
        $ECHO "Usage: $0 {start|stop|status|restart}"
        exit 1
        ;;
esac

