#!/bin/bash

# (C) CERN 2018
# author: Adam Wujek <adam.wujek@cern.ch>

function print_error {
    echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" | tee /dev/kmsg
    echo "!!!!!!!!!!! MEN A25: error during checking a bitstream version !!!!!!!!!!!!!!!!!" | tee /dev/kmsg
    echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" | tee /dev/kmsg
    echo -e "$1" | tee /dev/kmsg
    echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" | tee /dev/kmsg
    exit 1
}

#make sure install_drv.sh from the same dir as this file
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# "

SUPPORTED_BITSTREAMS_FILE="/proc/vme4l/supported_bitstreams"

# such link should be valid for all ACCs and CPUs
FPGA_LOAD_BIN=/usr/local/bin/fpga_load_a25

if ! [ -e "$FPGA_LOAD_BIN" ]; then
    print_error "fpga_load binary ($FPGA_LOAD_BIN) does not exist!"
fi

if ! [ -e "$SUPPORTED_BITSTREAMS_FILE" ]; then
    print_error "No proc entry with supported bitstreams ($SUPPORTED_BITSTREAMS_FILE)!"
fi

BITSTREAM_VER=`$FPGA_LOAD_BIN 1a88 4d45 d5 0 -n | grep gateware-revision: | cut -d " " -f 2`

echo $BITSTREAM_VER
if ! [ -n $BITSTREAM_VER ]; then
    print_error "Unable to get bitstream version!"
fi

while IFS='' read -r line ; do
    if [ "$line" = "$BITSTREAM_VER" ]; then
	echo "A25: Found supported bitstream $BITSTREAM_VER"
	exit 0
    fi
done < "$SUPPORTED_BITSTREAMS_FILE"

SUPPORTED_BITSTREAMS=`cat $SUPPORTED_BITSTREAMS_FILE`
print_error "Bitstream $BITSTREAM_VER is not supported by this driver!\n\
This VME bus driver supports the following bitstreams:\n\
$SUPPORTED_BITSTREAMS"
