#!/bin/bash

FPGA=$1
FPGAREG=${FPGA}reg
FPGAPFX=${2:-${FPGA^^}_}

SYSLOG_INFO="logger -s -p USER.INFO  -t ${FUNCNAME:-${0##*/}}"
SYSLOG_ERR="logger -s -p USER.ERR  -t ${FUNCNAME:-${0##*/}}"

#
# get the FPGA register.bit of a given irq device name
#
# $1: gp irq device name
#
function get_fpga_reg()
{
    # the interrupt name combines the register and bit field names
    # separated by underscores, for example SFP_RXLOS_INTR_PORT3
    #
    # this script expects this command to work:
    #
    #    <FPGA>reg <FPGAPFX>SFP_RXLOS_INTR_TST.PORT3

    fpga_reg="${FPGAPFX}${1%%_INTR_*}_INTR_TST.${1##*_INTR_}"

    echo ${fpga_reg}

    ${FPGAREG} ${fpga_reg} &> /dev/null
}


if [ "1" != "$#" ] && [ "2" != "$#" ]; then
    echo "usage: $0 <FPGA name> [ <FPGA register prefix> ]"
    exit 1
fi


for irqdev in /dev/cic_gpio/*; do

    gpiodev=$(readlink -f "${irqdev}")

    # keep only the interrupts dealing with our FPGA
    [ "${gpiodev}" = "${gpiodev/${FPGA}_cic}" ] && continue

    irqn="${irqdev##*/}"

    # figure out the interrupt register.bit
    mreg=$(get_fpga_reg ${irqn})
    if [ "0" != "$?" ]; then
        ${SYSLOG_ERR} "skipping ${irqn}, cannot resolve ${mreg}"
        continue
    fi

    ${SYSLOG_INFO} "triggering ${irqn}"

    # force an interrupt
    ( ${FPGAREG} ${mreg} 0 && \
      ${FPGAREG} ${mreg} 1  ) || {
        ${SYSLOG_ERR} "failed: ${FPGAREG} ${mreg} 1"
        exit 1
    }

done

exit 0
