#!/bin/bash
# Start/stop the xbutler daemon.
#
### BEGIN INIT INFO
# Provides:          xbutler
# Required-Start:    $syslog
# Required-Stop:     $syslog
# Should-Start:      $network auditd
# Should-Stop:       $network auditd
# Default-Start:     2 3 4 5
# Default-Stop:
# 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

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

test -f $DAEMON || exit 0

. /lib/lsb/init-functions

##############################
# Enable XILINX_XRT
##############################
log_daemon_msg  "---------------------" "${NAME}" 
log_daemon_msg  "Verifying XILINX_XRT" "${NAME}" 
log_daemon_msg  "---------------------" "${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
			log_daemon_msg  "Invalid XRT Version!" "${NAME}" 
			exit 0
		fi
	elif [ ${major_gt} -eq "0" ]; then
		log_daemon_msg  "Invalid XRT Version!" "${NAME}" 
		exit 0
	fi
	# enable XILINX_XRT
	. /opt/xilinx/xrt/setup.sh
else
	log_daemon_msg "Xilinx XRT not found on machine!" "${NAME}" 
	exit 0
fi


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