#!/bin/sh
#
# chkconfig: 235 99 05
# description: videoarchive patrol engine
#

# Source function library.
. /etc/init.d/functions

lockfile=/var/lock/subsys/patrol
statusfile=/var/sarch/wd/status
cmdfile=/var/sarch/wd/cmd
bootflag=/var/sarch/wd/booting
freshflag=/var/sarch/installed

RETVAL=0

wait_for_status() {
  local maxwait=60
  local i=0
  local status=$1

  while [ $i -lt $maxwait ] ; do
     [ $(cat $statusfile)x  = ${status}x ] && break
     sleep 5
     echo -n .
     i=$(($i+1))
  done
  if [ $i -lt $maxwait ] ; then
     return 0
  else
     echo "status didn't change"
     return 1
  fi
}

start() {
    echo start > $cmdfile
    echo -n $"Starting videoarchive: "
    # On system boot shepherd isn't running yet
    if [ -f $bootflag ]; then
        rm -f $bootflag
	touch $lockfile
        RETVAL=0
        return
    fi
    wait_for_status run
    RETVAL=$?
    if [ $RETVAL -eq 0 ] ; then
      touch $lockfile
      success
    else
      failure
    fi
}

stop() {
    echo stop > $cmdfile
    echo -n $"Stopping videoarchive: "
    wait_for_status stop
    # To assure vcadaemon was killed
    killall vcadaemon
    RETVAL=$?
    if [ $RETVAL -eq 0 ] ; then
      rm -f $lockfile
      success
    else
      failure
    fi
}

restart() {
    stop
    echo
    start
}

status() {
    echo 'Status: ' $(cat $statusfile)
}

# Check if it's a fresh installation
if [ -e $freshflag ];  then
   echo -n $"  Activation is required!"
   echo
   exit 3
fi

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

echo
exit $RETVAL
