#!/bin/sh
# Maximatecc 2016-09-20
# Daniel Nisses-Gagnér

CONFIGURATION_FILE="/opt/bin/FieldbusAccess_ConfigFile.json"

#
# function for testing if a can interface is initialized or not,
# to be able to start the fieldbusAccess runtime properly
#
is_can_initialized() {
CANSTATUS=0
if [ "$(cat /sys/class/net/can0/operstate)" != "down" ]; then
    	CANSTATUS=1
fi

if [ "$(cat /sys/class/net/can1/operstate)" != "down" ]; then
    	CANSTATUS=1
fi

if [ $CANSTATUS -eq 0 ]; then
    	echo "WARNING! No can interface initialized on the device" >> /var/log/fa.init
    	return 0;
fi
return 1; # CAN interface initialized
}

#
# Function holding startup, delaying no more than 1 second each time,
# until can interface is initialized or 5 consecutive tries have been done
#
hold_startup() {
counter=0
CAN="can0"
BITRATE="250000"
echo "" >> /var/log/fa.init

while [ "$counter" -le "10" ]
do
        if ! is_can_initialized
        then
            echo "CAN interface found, exit hold startup" >> /var/log/fa.init
            sleep 1
            return 1;
        fi
        echo "trying to initialize can interface" >> /var/log/fa.init
        ip link set $CAN type can bitrate $BITRATE
        #echo $BITRATE > /sys/class/net/$CAN/can_bittiming/bitrate
        ifconfig $CAN up
        counter=$((counter+1))
        sleep 1

done
echo "Failed to wait for can initialization in FieldbusAccess startup" >> /var/log/fieldbusaccess.error
return 0;
}


case "${1:-}" in
    start)


    # Wait for caninterface to initialize
    hold_startup;

    echo "Starting FieldbusAccess runtime" >> /var/log/fa.init

    # Start the server
    echo "Starting FieldbusAccess runtime"
    /opt/bin/fieldbusaccess $CONFIGURATION_FILE &

    ;;

    stop)
	echo "Stopping Fieldbus Access runtime..."
	
	# Get the PID of fieldbusaccess
	PROCESSID=$(pidof fieldbusaccess)

	if [ -z "$PROCESSID" ]
	then
		echo "fieldbusaccess process not found!"
	else
		# Send SIGTERM to fieldbusaccess
		kill -15  $PROCESSID
	fi
    ;;

    *)
    echo "Usage: $0 {start|stop}"
    RETVAL=2
    ;;
esac

exit 0
