#!/usr/bin/env bash
set -euo pipefail
case $1 in   
post)
    # Replace this with your SPI_HID driver if its different
    DRV="/sys/bus/spi/drivers/spi_hid"

    echo "driver: $DRV"

    # Find bound devices. The driver dir contains symlinks for every bound
    # device, plus regular files (bind/unbind/uevent/module). Filter for
    # entries matching spiN.M.
    devs=( )
    for entry in "$DRV"/*; do
        name="$(basename "$entry")"
        [[ "$name" =~ ^spi[0-9]+\.[0-9]+$ ]] || continue
        [ -L "$entry" ] || continue
        devs+=("$name")
    done

    if [ "${#devs[@]}" -eq 0 ]; then
        echo "no bound devices found${TARGET:+ matching $TARGET}" >&2
        exit 1
    fi
    echo "devices: ${devs[*]}"

    for d in "${devs[@]}"; do
        echo "unbinding $d"
        # The unbind sysfs write can fail if the device is wedged; keep going.
        if ! printf '%s' "$d" > "$DRV/unbind" 2>/dev/null; then
            echo "  warning: unbind failed (maybe already unbound)" >&2
        fi
    done

    sleep 0.5

    for d in "${devs[@]}"; do
        echo "rebinding $d"
        if ! printf '%s' "$d" > "$DRV/bind"; then
            echo "  bind failed for $d" >&2
            exit 1
        fi
    done

    echo done.

    ;; 
esac
