#!/bin/bash
#
# Start/stop the xbutler daemon.
#
# chkconfig: 2345 90 60
### BEGIN INIT INFO
# Short-Description: xButler is a service that manages Xilinx FPGA resources using Xilinx Runtime (XRT).
# Description:       xButler is a service that manages Xilinx FPGA resources using Xilinx Runtime (XRT).
### END INIT INFO

# Source function library.
. /etc/init.d/functions
. /lib/lsb/init-functions

PATH=/bin:/usr/bin:/sbin:/usr/sbin
DESC="xButler daemon"
NAME=xbutler
DAEMON=/usr/sbin/xbutler
PIDFILE=/var/run/xbutler.pid
SCRIPTNAME=/etc/rc.d/init.d/"$NAME"

test -f $DAEMON || exit 0

##############################
# Enable XILINX_XRT
##############################
echo  "---------------------" "${NAME}" 
echo  "Verifying XILINX_XRT" "${NAME}" 
echo  "---------------------" "${NAME}" 
if [ -f /opt/xilinx/xrt/include/version.h ]; then
	info_xrt=$(cat /opt/xilinx/xrt/include/version.h | grep xrt_build_version\\[ | sed 's/[^0-9.]*//g')
	major=$(echo ${info_xrt} | cut -f1 -d ".")
	minor=$(echo ${info_xrt} | cut -f2 -d ".")
	major_gt=$(expr ${major} \> 2)
	major_eq=$(expr ${major} = 2)
	minor_=$(expr ${minor} \>= 2)
	# check version
	if [ ${major_eq} -eq "1" ]; then
		if [ ${minor_} -eq "0" ]; then
			echo  "Invalid XRT Version!" "${NAME}" 
			exit 0
		fi
	elif [ ${major_gt} -eq "0" ]; then
		echo  "Invalid XRT Version!" "${NAME}" 
		exit 0
	fi
	# enable XILINX_XRT
	. /opt/xilinx/xrt/setup.sh
else
	echo "Xilinx XRT not found on machine!" "${NAME}" 
	exit 0
fi


##############################
# Action
##############################
case "$1" in
start)	echo "Starting periodic command scheduler" "${NAME}"
	start_daemon -p $PIDFILE $DAEMON $EXTRA_OPTS
        echo $?
	;;
stop)	echo "Stopping periodic command scheduler" "${NAME}"
        killproc -p $PIDFILE
        RETVAL=$?
        [ $RETVAL -eq 0 ] && [ -e "$PIDFILE" ] && rm -f $PIDFILE
        echo $RETVAL
        ;;
restart) echo "Restarting periodic command scheduler" "${NAME}" 
        $0 stop
        $0 start
        ;;
status)
        status -p $PIDFILE && exit 0 || exit $?
        ;;
*)	echo "Usage: ${SCRIPTNAME} {start|stop|status|restart}"
        exit 2
        ;;
esac
exit 0
