#!/bin/bash
#< init.d script for rsyncd

BASENAME="/bin/basename"
ECHO="/bin/echo"
PGREP="/usr/bin/pgrep"
PKILL="/usr/bin/pkill"
RSYNC="/usr/local/bin/rsync"
RSYNC_OPTIONS="--daemon"
SLEEP="/usr/bin/sleep"

function print_usage {
   {
      ${ECHO} "Usage: $( ${BASENAME} $0 ) {start|stop|restart|status}"
   } >&2   
}

function start {
   ${PGREP} -f "${RSYNC} ${RSYNC_OPTIONS}" >/dev/null 2>&1
   if [ "$?" -eq "0" ]; then
      ${ECHO} "${RSYNC} ${RSYNC_OPTIONS} - Already started" && exit 1
   fi
   ${RSYNC} ${RSYNC_OPTIONS}
   ${SLEEP} 2
   ${PGREP} -f "${RSYNC} ${RSYNC_OPTIONS}" >/dev/null 2>&1
   if [ "$?" -eq "0" ]; then 
      ${ECHO} "${RSYNC} ${RSYNC_OPTIONS} - Started OK"
   else
      ${ECHO} "${RSYNC} ${RSYNC_OPTIONS} - Failed to start"
      ext 1
   fi
}

function stop {
   ${PGREP} -f "${RSYNC} ${RSYNC_OPTIONS}" >/dev/null 2>&1
   if [ "$?" -ne "0" ]; then
      ${ECHO} "${RSYNC} ${RSYNC_OPTIONS} - Already started" && exit 1
   fi
   ${PKILL} -f "${RSYNC} ${RSYNC_OPTIONS}" >/dev/null 2>&1
   if [ "$?" -ne "0" ]; then
      ${ECHO} "${RSYNC} ${RSYNC_OPTIONS} - Could not kill process" && exit 1
   else
      ${ECHO} "${RSYNC} ${RSYNC_OPTIONS} - Stopped OK"
   fi
}

function restart {
   stop && ${SLEEP} 2 && start
}

function status {
   ${PGREP} -f "${RSYNC} ${RSYNC_OPTIONS}" >/dev/null 2>&1
   if [ "$?" -ne "0" ]; then
      ${ECHO} "${RSYNC} ${RSYNC_OPTIONS} - Not started"
   else
      RSYNC_PID=$( ${PGREP} -f "${RSYNC} ${RSYNC_OPTIONS}" )
      ${ECHO} "${RSYNC} ${RSYNC_OPTIONS} - Started [PID:${RSYNC_PID}]"
   fi
}

case $1 in
   'start'   ) start                 ;;
   'stop'    ) stop                  ;;
   'restart' ) restart               ;;
   'status'  ) status                ;;
   *         ) print_usage && exit 1 ;;
esac

exit 0