#! /bin/bash

export_gpio() {
    local TARGET_GPIOCHIP=moxa-gpio
    local GPIOCHIP_NAME=gpiochip
    local GPIO_FS_PATH=/sys/class/gpio
    local GPIO_EXPORT="export"

    if [ x"$1" == x"unexport" ]; then
        GPIO_EXPORT="unexport"
    fi

    #
    # Export GPIOs
    #
    ls $GPIO_FS_PATH | grep $GPIOCHIP_NAME | while read -r chip ; do
        GPIO_LABEL=$(cat $GPIO_FS_PATH/$chip/label)
        if [[ "$GPIO_LABEL" != *"$TARGET_GPIOCHIP"* ]]; then
            continue
        fi

        pinstart=$(echo $chip | sed s/$GPIOCHIP_NAME/\\n/g)
        count=$(cat $GPIO_FS_PATH/$chip/ngpio)
        for (( i=0; i<${count}; i++ )); do
            echo $((${pinstart}+${i})) > $GPIO_FS_PATH/$GPIO_EXPORT 2>/dev/null
        done
    done
}

case "$1" in
    start)
        export_gpio
        ;;
    stop)
        export_gpio unexport
        ;;
    *)
        echo "Usage: $0 start|stop" >&2
        exit 3
        ;;
esac


