#! /bin/sh
#

# gsync     Start/Stop the Gandi backup framework
#
# chkconfig: 2345 55 25
# description: Gandi backup framework using plugin to backup data
# processname: gsync
# config: /etc/sysconfig/gsync
# pidfile: /var/run/gsync.pid
#

### BEGIN INIT INFO
# Provides:          gsync
# Required-Start: $syslog
# Required-Stop: 
# Default-Start: 2 3 4 5
# Default-Stop:
# Short-Description: Start/stop Gandi backup framework
### END INIT INFO

if [ -f /etc/rc.d/init.d/functions ]; then
    # source function library
    . /etc/rc.d/init.d/functions
fi


PATH=/sbin:/bin:/usr/sbin:/usr/bin
NAME=gsync
DAEMON_NAME=$NAME.py
DAEMON=/usr/sbin/$DAEMON_NAME
DESC="Gandi sync"
DAEMON_OPTS=""
PID_FILE="/var/run/$NAME.pid"

test -x $DAEMON || exit 0

if [ -f /etc/default/$NAME ] ; then
  . /etc/default/$NAME
else
    if [ -f /etc/sysconfig/$NAME ]; then
        . /etc/sysconfig/$NAME
    fi
fi

set -e

do_stop() {
    echo -n "Stopping $DESC: "
    if [ -x /sbin/start-stop-daemon ]; then
    	start-stop-daemon --oknodo --retry 5 --signal TERM --stop --quiet \
        	--pidfile $PID_FILE
    else
	if [ -f $PID_FILE ]; then
		pkill $DAEMON_NAME && success || failure
    		RETVAL=$?
		echo
    		[ $RETVAL -eq 0 ] && [ -f $PID_FILE ] &&  rm -f $PID_FILE
	fi
    fi
    echo "$NAME."
}

which_py() {
  #temporary workaround

  pylist=`ls -r /usr/bin/python2.[456]`
  if [ $? != 0 ]; then
    pylist="/usr/bin/python"
  fi

  echo $pylist | awk '{print $1}'
}

do_start() {
    echo -n "Starting $DESC: "
    if [ -x /sbin/start-stop-daemon ]; then
        start-stop-daemon --start --quiet $BACKGROUND --pidfile $PID_FILE \
    	    --exec `which_py` -- $DAEMON $DAEMON_OPTS
    else
        [ -f $PID_FILE ] && return
	# use --user to run the daemon under the specified uid
    	$DAEMON $DAEMON_OPTS && success || failure
	RETVAL=$?
    	echo
    	[ $RETVAL -eq 0 ] && touch $PID_FILE
    fi
    echo "$NAME."
}                                                                                                    

case "$1" in
  start)
      do_start
  ;;
  stop)
      do_stop
  ;;
  restart|force-reload)
      do_stop
      do_start
  ;;
  *)
      echo "Usage: /etc/init.d/$NAME {start|stop|restart|force-reload}" >&2
      exit 1
  ;;                                                                                                                    
esac                                                                                                                    

exit 0
