#!/bin/bash
# turn on/off a certain amount of IO from the FASEC FMC gpiochips
# TODO: check for gpiochip i2c address!

readonly FMC1CHIP=890 # addr 74
readonly FMC2CHIP=874 # addr 75
# for gpiochip addr, see https://wikis.cern.ch/display/TEABT/FIDS+integration
# if part of FMCnARR array, 50 Ohm termination will be enabled for that input
declare -a FMCnARR=() 
declare -a FMCnLEDS=(885 886 901 902)
declare -a FMCnHighImp=(874 875 876 877 878 879 880 881 882 883 890 891 894 895 896 899 892 893 897 898)

if [ ! -d "/sys/class/gpio/gpiochip"$FMC1CHIP ]; then
    echo "WARNING: not found FMC1 gpiochip"$FMC1CHIP
fi
if [ ! -d "/sys/class/gpio/gpiochip"$FMC2CHIP ]; then
    echo "WARNING: not found FMC2 gpiochip"$FMC2CHIP    
fi

for i in "${FMCnHighImp[@]}"
do
    gpio="$i"
    # exporting first cause possible new IC (not configured) connected
    if [ -d "/sys/class/gpio/gpio"$gpio ]; then
	echo $gpio > /sys/class/gpio/unexport
    fi
    echo $gpio > /sys/class/gpio/export
    echo out > "/sys/class/gpio/gpio"$gpio"/direction"
    echo 0 > "/sys/class/gpio/gpio"$gpio"/value"
done

for i in "${FMCnARR[@]}"
do
    gpio="$i"
    # exporting first cause possible new IC (not configured) connected
    if [ -d "/sys/class/gpio/gpio"$gpio ]; then
	echo $gpio > /sys/class/gpio/unexport
    fi
    echo $gpio > /sys/class/gpio/export
    echo out > "/sys/class/gpio/gpio"$gpio"/direction"
    echo 1 > "/sys/class/gpio/gpio"$gpio"/value"
done

# switch on FMC LEDs to indicate proper configuration
for i in "${FMCnLEDS[@]}"
do
    gpio="$i"
    # exporting first cause possible new IC (not configured) connected
    if [ -d "/sys/class/gpio/gpio"$gpio ]; then
	echo $gpio > /sys/class/gpio/unexport
    fi
    echo $gpio > /sys/class/gpio/export
    echo out > "/sys/class/gpio/gpio"$gpio"/direction"
    echo 0 > "/sys/class/gpio/gpio"$gpio"/value"
done
