#!/usr/bin/env bash

# $Header: https://svn.mpia.de/gulli/TwiceAsNice/branch/unstable/TwiceAsNice/basda/src/Interface/rcbasdard.sh.in 15737 2019-05-15 10:16:16Z briegel $

# Sample use of the restart option (see config/system/*.lr) :
#   rcbasdard.sh restart lircs.moe.smc.b-dx

test "x$INSROOT" = "x" && . /opt/tan/etc/tan.sh
test -d $INSROOT/var/run/ || mkdir -p $INSROOT/var/run/
test -d $INSROOT/log/run/ || mkdir -p $INSROOT/var/log/
test -d $TMPDIR/ || mkdir -p $TMPDIR/


if test $# -lt 2 ; then
  echo "usage: rcbasdard {start|stop|restart} PIDFILE";
  exit -1
fi

pidfile=$INSROOT/var/run/$2.pid
logfile=$INSROOT/var/log/$2.log

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$INSROOT/lib/shins

case $1 in
    start)
       if test -e $pidfile; then
          oldpid=`cat $pidfile`; 
          oldrun=`lsof -t -p $oldpid`;
          if test "x$oldpid" = "x$oldrun"; then
            echo "basdard already running with #$oldpid"
            exit -1
          fi
       fi 
       shift
       shift
#       exec 2>&1 $INSROOT/bin/basdard $* 1> $logfile &
#       exec 2>&1 $INSROOT/bin/basdard --LOGGER.BUFFERED=true --LOGGER.TYPE="ExtColor" --LOGGER.LEVEL=INFO $* | /usr/sbin/rotatelogs2 -n 3 $logfile 10K &
       exec 2>&1 $INSROOT/bin/basdard --LOGGER.BUFFERED=true --LOGGER.TYPE="ExtColor" --LOGGER.LEVEL=INFO $* 1>> $logfile &
       pid=$!
       run=`lsof -t -p $pid`
       sleep 0.1
       if test "x$pid" = "x$run"; then
         echo $! > $pidfile;
       else
	 echo "error: could not start basdard $*"
       fi
       ;;
    restart)
       if test -e $pidfile; then
          oldpid=`cat $pidfile`; 
          # recover the old --CONFIG argument
          oldconf=$(ps -o args -h -p ${oldpid} | awk '{print $NF}')
       fi
       shift
       $0 stop $*
       $0 start $* ${oldconf}
       ;;
     stop)  
       kill `cat $pidfile`;
       ii=20;
       while [ "$ii" -gt 0 ];
       do
         pid=`cat $pidfile`
         echo $ii
         if ! ps -p $pid>/dev/null; then 
           rm $pidfile;
           exit 0;
         fi
         sleep 0.1;
         ii=`expr $ii - 1`;
       done
       kill -9 `cat $pidfile`; 
       rm $pidfile;
       ;;
     *)  
       echo "usage: xyz {start|stop|restart} PIDFILE" ;;
esac
exit 0
