#!/usr/bin/env bash

function update_device_fw()
{
    AJA_FW_TOOL=%{_bindir}/ntv2firmwareinstaller
    name=$1
    fw_file=$2
    if [ -e $AJA_FW_TOOL ] && [ -e $fw_file ]; then
        AJA_FW_STATUS=`"$AJA_FW_TOOL" --device $name -i $fw_file`
        # This works out whether the provided AJA FW is different to that on the card
        # Output before munging is like this:
        #
        # /tmp/corvid44_10-6-15.bit  Corvid44    2015/10/06 15:54:06  corvid_44
        # Current 'Corvid44 0':  Firmware '2015/10/06 15:54:06', serial '00T72237'
        #
        if [[ -n "$AJA_FW_STATUS" ]] ; then
            TEST=`echo -e "$AJA_FW_STATUS" | grep -o "[0-9]\{4\}\/[0-9]\{2\}\/[0-9]\{2\}" | sort | uniq -c | cut -c 7- | cut -d' ' -f1`
            if [[ $TEST == "2" ]]; then
              echo "AJA card $name is up to date"
            else
              "$AJA_FW_TOOL" --progress --device $name $fw_file
            fi
        else
            echo "Missing AJA card or update file needed for $name"
        fi
    else
        echo "FW file or AJA software missing"
    fi
}

update_device_fw CorVid24 %{firmwaredir}/corvid24quad*.bit
update_device_fw CorVid44 %{firmwaredir}/corvid44*.bit

