#!/bin/bash
#
#
#
# Start on runlevels 3, 4 and 5. Start late, kill early.
# chkconfig: 345 95 05
#
#
#!/bin/bash

### BEGIN INIT INFO
# Provides: online-backup
# Required-Start: $remote_fs
# Required-Stop: $remote_fs
# Should-Start:
# Default-Start: 3 5
# Default-Stop: 0 1 2 6
# Description: Start the Local Management Daemon
### END INIT INFO

# absolute path to executable binary
progpath='/opt/local/Online Backup/bin/cbbWebAccess'

# binary program name
prog=$(basename "$progpath")

# pid file
pidfile="/var/run/${prog}.pid"

# make sure full path to executable binary is found
! [ -x "$progpath" ] && echo "$progpath executable not found" && exit 1

eval_cmd() {
 local rc=$1
 if [ $rc -eq 0 ]; then
   echo '[  OK1  ]'
 else
   echo '[FAILED1]'
 fi
 return $rc
}

start() {
 # see if running

 NewDaemonProc=`ps aux | grep cbbWebAccess | grep "Online Backup" | grep -v grep | wc -l `
 if [ "$NewDaemonProc" != "0" ]; then
     echo Service is already running
     return 0
 fi

 printf "%-50s%s" "Starting $prog: " ''
 "$progpath" >/dev/null 2>&1 &
 # save pid to file if you want

 echo $! > $pidfile

 sleep 1

 NewDaemonProc=`ps aux | grep cbbWebAccess | grep "Online Backup" | grep -v grep | wc -l `
 if [ "$NewDaemonProc" != "0" ]; then
     echo '[  OK  ]'
 else
     echo '[  FAIL  ]'
 fi
}

stop() {

SENDED=false
COUNT=1
while true; do
    NewDaemonProc=`ps aux | grep cbbWebAccess | grep "Online Backup" | grep -v grep | wc -l`
    if [ "$NewDaemonProc" != "0" ]; then
        if [  $SENDED == false ]; then
            LocalPid=`ps aux | grep cbbWebAccess | grep "Online Backup" | grep -v grep | awk '{print $2}'`
            kill -SIGINT $LocalPid
        fi

        sleep 1
        COUNT=$((COUNT+1))

        if [ $((COUNT)) -gt 3 ]; then
            kill -9 $LocalPid
            echo '[  OK  ]'
            break;
        fi

        NewDaemonProc=`ps aux | grep cbbWebAccess | grep "Online Backup" | grep -v grep | wc -l`
        if [ "$NewDaemonProc" == "0" ]; then
            echo '[  OK  ]'
            break
        fi
    else
        echo Service already stopped
        break
    fi
done

}

status() {
 # see if running

NewDaemonProc=`ps aux | grep cbbWebAccess | grep "Online Backup" | grep -v grep | wc -l `
if [ "$NewDaemonProc" != "0" ]; then
echo '[ Running ]'
else
echo '[ Stopped ]'
fi
}

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

exit $?

