#!/bin/bash

# Usage: port-map.sh [-d] [device_type] [port]
# -d: return block device (/dev/sdX) instead of USB topology
# device_type: 4|5|auto|rpi4|rpi5 (Pi model, auto-detected if not provided)
# port: B1|B2|T1|T2 (optional, returns specific mapping)

get_block_device() {
    local usb_path="$1"
    for dev in /sys/block/sd*; do
        [ -e "$dev/device" ] || continue
        device_path=$(readlink -f "$dev/device")
        if [[ "$device_path" == *"$usb_path"* ]]; then
            echo "/dev/$(basename "$dev")"
            return
        fi
    done
}

use_device=false
[ "$1" = "-d" ] && { use_device=true; shift; }

device_type="$1"
port="$2"

# Auto-detect Pi model if not provided or if provided as string
if [[ -z "$device_type" ]]; then
    if grep -q "Pi 5" /proc/device-tree/model 2>/dev/null; then
        device_type="5"
    elif grep -q "Pi 4" /proc/device-tree/model 2>/dev/null; then
        device_type="4"
    else
        device_type="5"  # Default fallback
    fi
else
    # Convert model string to number
    case "$device_type" in
        "rpi5"|"pi5"|"5") device_type="5" ;;
        "rpi4"|"pi4"|"4") device_type="4" ;;
        "auto"|"") 
            if grep -q "Pi 5" /proc/device-tree/model 2>/dev/null; then
                device_type="5"
            elif grep -q "Pi 4" /proc/device-tree/model 2>/dev/null; then
                device_type="4"
            else
                device_type="5"  # Default fallback
            fi
            ;;
        *) 
            echo "Unsupported device type: $device_type"
            exit 1
            ;;
    esac
fi

case "$device_type" in
    5)
        declare -A pi5_map=(
            ["B1"]="1-2"
            ["B2"]="3-1"
            ["T1"]="1-1"
            ["T2"]="3-2"
        )
        port_map=pi5_map
        ;;
    4)
        declare -A pi4_map=(
            ["B1"]="1-1.1"
            ["B2"]="1-1.2"
            ["T1"]="1-1.3"
            ["T2"]="1-1.4"
        )
        port_map=pi4_map
        ;;
    *)
        echo "Unsupported device type: $device_type"
        exit 1
        ;;
esac

if [ -n "$port" ]; then
    eval "mapping=\${${port_map}[$port]}"
    if [ "$use_device" = true ]; then
        get_block_device "$mapping"
    else
        echo "$mapping"
    fi
else
    for p in B1 B2 T1 T2; do
        eval "mapping=\${${port_map}[$p]}"
        if [ "$use_device" = true ]; then
            device=$(get_block_device "$mapping")
            echo "$p ${device:-not found}"
        else
            echo "$p $mapping"
        fi
    done
fi
