#!/bin/bash
#
# /etc/init.d/driveclient
#
# Starts Rackspace Backup Agent
#
# chkconfig: 345 95 5
# description: Runs Rackspace Backup Agent
# processname: driveclient

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

test -x /usr/local/bin/driveclient || exit 0

RETVAL=0
DAEMON="/usr/local/bin/driveclient"
PIDFILE="/var/run/driveclient.pid"


#
# See how we were called.
#

prog="driveclient"

start() {
      echo -n $"Starting $prog: "
      export HOME=/root
      /usr/local/bin/driveclient --daemon
      RETVAL=$?
    echo
  return $RETVAL
}

stop() {
# Retry 60 times, with interval of 5 seconds.
  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
}


restart() {
  stop
  start
}

reload() {
  restart
}

status_at() {
  status /usr/local/bin/driveclient
}

case "$1" in
start)
  start
  ;;
stop)
  stop
  ;;
reload|restart)
  restart
  ;;
condrestart)
    restart
;;
status)
  status_at
  ;;
*)
  echo $"Usage: $0 {start|stop|restart|condrestart|status}"
  exit 1
esac

exit $?
exit $RETVAL

