#!/bin/bash
set -e

function pio-export-unexport {
    for GPIOCHIP in /sys/class/gpio/gpiochip*
    do
        case $(cat $GPIOCHIP/label) in
            de01-pio-out|de01-pio-int-in)
                FIRST=$(cat $GPIOCHIP/base)
                let "LAST = FIRST + $(cat $GPIOCHIP/ngpio) - 1"
                for GPIO in $(seq $FIRST $LAST)
                do
                    echo $GPIO > /sys/class/gpio/$1
                done
            ;;
        esac
    done
}

# clean up
pio-export-unexport unexport || true
rmmod de01 || true

# get device path
DEV=/sys/bus/pci/devices/$(lspci -mm -D -d :de01 | cut -d ' ' -f 1)
test -d $DEV

echo "Dump BAR0:"
./mmap_dump $DEV/resource0 | hd

# all kernel printk on console
#echo 8 > /proc/sys/kernel/printk
#tail -n 0 -f /var/log/kern.log &

insmod de01.ko
trap "rmmod de01" EXIT

pio-export-unexport export
trap "pio-export-unexport unexport ; rmmod de01" EXIT

echo "Blinking LEDs using GPIO interface..."
for LED in /sys/class/gpio/*led*
do
    echo $LED
    echo out > $LED/direction
    echo 1 > $LED/value
    sleep 0.5
    echo 0 > $LED/value
done

echo "Blinking LEDs using LED interface..."
for LED in /sys/class/leds/de01:*
do
    echo $LED
    cp $LED/max_brightness $LED/brightness
    sleep 0.5
    echo 0 > $LED/brightness
done

echo "Value of Function Button:" $(cat /sys/class/gpio/function-button/value)

echo both > /sys/class/gpio/function-button/edge
echo "Press Function Button to continue..."
./wait_int /sys/class/gpio/function-button/value
echo "Interrupt from Function Button received."
