#!/bin/bash
### BEGIN INIT INFO
# Provides:         driveclient
# Required-Start:   $syslog $time $remote_fs
# Required-Stop:     $syslog $time $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:     0 1 6
# Short-Description: Rackspace Backup Driveclient
# Description:       Debian init script for the Rackspace backup Driveclient
### END INIT INFO

set -e

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin
DAEMON="/usr/local/bin/driveclient"
PIDFILE="/var/run/driveclient.pid"

test -x $DAEMON || exit 0

. /lib/lsb/init-functions

stop() {
# Retry 60 times, with interval of 5 seconds.
  log_daemon_msg "Stopping Rackspace Backup Driveclient" ""
  echo -n $"Stopping $prog: "
  local retry=60
  local RETVAL=1
  local PROC=0

  if ps -ewwo pid,args | grep [d]riveclient |grep daemon > /dev/null 2>&1
  then
    if [ -f "/var/run/driveclient.pid" ];
    then
      PROC=`cat /var/run/driveclient.pid`
      kill $PROC > /dev/null 2>&1
    fi

    if ps -ewwo pid,args | grep [d]riveclient |grep daemon > /dev/null 2>&1
    then
      RETVAL=1
    else
      RETVAL=0
    fi

    while [ "$RETVAL" -eq 1 -a "$retry" -gt 0 ]; do
      sleep 5
      retry=$(($retry -1))
      if ps -ewwo pid,args | grep [d]riveclient |grep daemon > /dev/null 2>&1
      then
        RETVAL=1
      else
        rm -f $PIDFILE
        echo
        RETVAL=0
      fi
    done

    return 0
  fi
}

case "$1" in
    start)
  log_daemon_msg "Starting Rackspace Backup Driveclient" ""
    export HOME=/root
  start_daemon $DAEMON --daemon
  log_end_msg $?
    ;;
  stop)
  stop
  log_end_msg $?
    ;;
  force-reload|restart)
    $0 stop
    $0 start
    ;;
  status)
    status_of_proc $DAEMON driveclient && exit 0 || exit $?
    ;;
  *)
    echo "Usage: /etc/init.d/driveclient {start|stop|restart|force-reload|status}"
    exit 1
    ;;
esac

exit 0

