#!/bin/bash

##########################################################
# Global Functions
##########################################################

export_pin () {
    NUMBER=$1
    DIR=$2
    if [ ! -d "/sys/class/gpio/gpio${NUMBER}" ]; then
        echo "${NUMBER}" > /sys/class/gpio/export
    fi

    echo "$DIR" > /sys/class/gpio/gpio${NUMBER}/direction

    #if [ "$DIR" == "in" ]; then
    #    echo "both" > /sys/class/gpio/gpio${NUMBER}/edge
    #fi
}

set_value () {
    NUMBER=$1
    VALUE=$2
    export_pin "${NUMBER}" out
    
    echo "${VALUE}" > /sys/class/gpio/gpio${NUMBER}/value
}


# Init GPIOs

# run led GPIO 7
export_pin 578 out
# fan GPIO 4
export_pin 575 out

# Enable I2C5 (AF 5, no pull)
#dtoverlay i2c5
# gpio 12
pinctrl set 12 a5 pn
# gpio 13
pinctrl set 13 a5 pn

# Set interrupt pins
pinctrl set 27 ip pu
pinctrl set 17 ip pu
pinctrl set 19 ip pu
pinctrl set 26 ip pu

GPIOCHIPLIST=$(ls -1 /sys/class/gpio/ | grep gpiochip)
IFS=$'\n'
for chip in $GPIOCHIPLIST; do
    label=$(cat /sys/class/gpio/${chip}/label)
    if [ "$label" == "mcp23017" ]; then
        echo "Found MCP23017 at ${chip}"
        base=$(cat /sys/class/gpio/${chip}/base)
        count=$(cat /sys/class/gpio/${chip}/ngpio)
        if [ $count -ne 16 ]; then
            echo "Invalid count $count of MCP23017" > /sys/stderr
        fi

        # Inputs
        for n in {0..7}; do
            pin=$(expr $base + $n)
            echo "Input $n: $pin"
            export_pin $pin "in"
        done

        # Outputs
        for n in {8..15}; do
            pin=$(expr $base + $n)
            echo "Output $n: $pin"
            export_pin $pin "out"
            set_value $pin "0"
        done
    fi
done

 
