#!/usr/bin/env bash
#
# iPod Auto-Mounter for macOS
# ---------------------------
# Looks for connected iPods (Vendor ID = Apple 0x05ac),
# matches them against known Product IDs,
# detects the filesystem, and mounts them under /Volumes/<VolumeName>.
#

# ---------------------------
# Prevent Finder from showing "Restore iPod" popup
killall AMPDeviceDiscoveryAgent 2>/dev/null
# ---------------------------

# ---------------------------
# CONFIG: Supported iPod Product IDs → Model Names
declare -A IPOD_MODELS=(
  ["1201"]="iPod with dock connector (3rd generation)"
  ["1202"]="iPod (1st and 2nd generation)"
  ["1203"]="iPod with Click Wheel (4th generation)"
  ["1204"]="iPod Photo / iPod with color display"
  ["1205"]="iPod mini (1st and 2nd generation)"
  ["1209"]="iPod with video (5th generation)"
  ["120A"]="iPod nano"
  ["1220"]="iPod nano (2nd generation) (DFU Mode)"
  ["1221"]="iPod shuffle (2nd generation) (DFU Mode)"
  ["1223"]="iPod classic (6th gen, DFU Mode) / iPod nano (3rd gen, DFU Mode)"
  ["1225"]="iPod nano (4th generation) (DFU Mode)"
  ["1231"]="iPod nano (5th generation) (DFU Mode)"
  ["1232"]="iPod nano (6th generation) (DFU Mode)"
  ["1234"]="iPod nano (7th generation) (DFU Mode)"
  ["1240"]="iPod nano (2nd generation) (WTF Mode)"
  ["1241"]="iPod classic (6th generation) (Late 2007, WTF Mode)"
  ["1242"]="iPod nano (3rd generation) (WTF Mode)"
  ["1243"]="iPod nano (4th generation) (WTF Mode)"
  ["1245"]="iPod classic (6th generation) (Late 2008, WTF Mode)"
  ["1246"]="iPod nano (5th generation) (WTF Mode)"
  ["1247"]="iPod classic (6th generation) (Late 2009, WTF Mode)"
  ["1248"]="iPod nano (6th generation) (WTF Mode)"
  ["1249"]="iPod nano (7th generation) (Late 2012, WTF Mode)"
  ["124A"]="iPod nano (7th generation) (Mid 2015, WTF Mode)"
  ["1250"]="iPod classic (6th generation) (Late 2012, WTF Mode)"
  ["1260"]="iPod nano (2nd generation)"
  ["1261"]="iPod classic (6th generation)"
  ["1262"]="iPod nano (3rd generation)"
  ["1263"]="iPod nano (4th generation)"
  ["1265"]="iPod nano (5th generation)"
  ["1266"]="iPod nano (6th generation)"
  ["1267"]="iPod nano (7th generation)"
  ["1300"]="iPod shuffle (1st and 2nd generation)"
)
APPLE_VENDOR_ID="0x05ac"   # All iPods report Apple’s USB Vendor ID
# ---------------------------

echo "🔍 Scanning for connected iPods..."

# ---------------------------
# Capture all matching BSD names into a variable
MATCHES=$(system_profiler SPUSBDataType | awk -v vids="$APPLE_VENDOR_ID" '
    /Product ID:/ {pid=$3}
    /Vendor ID:/  {vid=$3}
    /BSD Name:/   {bsd=$3; if (vid!="" && pid!="" && bsd!="") print vid, pid, bsd}
')
# ---------------------------

# ---------------------------
# If no matches found, print message and exit
if [[ -z "$MATCHES" ]]; then
    echo "⚠️ No iPod detected."
    exit 0
fi
# ---------------------------

# ---------------------------
# Process each matched iPod
echo "$MATCHES" | while read -r VENDOR_ID PRODUCT_ID BSD_NAME; do
    # Only continue if Vendor is Apple
    [[ "$VENDOR_ID" != "$APPLE_VENDOR_ID" ]] && continue

    # Only continue if BSD name is a partition (diskXsY, not diskX)
    [[ "$BSD_NAME" =~ s[0-9]+$ ]] || continue

    # Strip "0x" from PRODUCT_ID
    PID="${PRODUCT_ID#0x}"

    # Lookup model name
    MODEL_NAME="${IPOD_MODELS[$PID]}"
    [[ -z "$MODEL_NAME" ]] && MODEL_NAME="Unknown iPod model"

    DRIVE_IDENTIFIER="/dev/$BSD_NAME"
    echo "✅ Found $MODEL_NAME (Product ID $PID) at $DRIVE_IDENTIFIER"

    # ---------------------------
    # Extract volume metadata
    VOLUME_NAME=$(diskutil info -plist "$DRIVE_IDENTIFIER" | \
        plutil -extract VolumeName xml1 -o - - | \
        sed -n 's:.*<string>\(.*\)</string>.*:\1:p')

    FS_TYPE=$(diskutil info -plist "$DRIVE_IDENTIFIER" | \
        plutil -extract FilesystemName xml1 -o - - | \
        sed -n 's:.*<string>\(.*\)</string>.*:\1:p')

    MOUNTPOINT="/Volumes/$VOLUME_NAME"

    echo "  Volume name: $VOLUME_NAME"
    echo "  Filesystem:  $FS_TYPE"
    # ---------------------------

    # Is this device already mounted?
    CURRENT_MOUNT=$(diskutil info -plist "$DRIVE_IDENTIFIER" | \
        plutil -extract MountPoint xml1 -o - - | \
        sed -n 's:.*<string>\(.*\)</string>.*:\1:p')

    if [[ "$CURRENT_MOUNT" == "$MOUNTPOINT" && -n "$CURRENT_MOUNT" ]]; then
        echo "⚠️  $VOLUME_NAME already mounted at $MOUNTPOINT"
        continue
    fi

    # Handle leftover directory if not mounted
    if [[ -z "$CURRENT_MOUNT" && -d "$MOUNTPOINT" ]]; then
        echo "🧹 Removing stale mountpoint $MOUNTPOINT"
        sudo rm -rf "$MOUNTPOINT"
    fi

    # Ensure mountpoint exists
    sudo mkdir -p "$MOUNTPOINT"

    # ---------------------------
    # Mount depending on filesystem
    case "$FS_TYPE" in
        "MS-DOS FAT32"|"MS-DOS"|"FAT32")
            echo "📀 Mounting $VOLUME_NAME as FAT32..."
            sudo mount_msdos "$DRIVE_IDENTIFIER" "$MOUNTPOINT"
            ;;
        "Journaled HFS+"|"HFS+"|"Mac OS Extended")
            echo "📀 Mounting $VOLUME_NAME as HFS+..."
            sudo mount_hfs "$DRIVE_IDENTIFIER" "$MOUNTPOINT"
            ;;
        *)
            echo "❌ Unsupported filesystem: $FS_TYPE"
            ;;
    esac

    echo "✅ Mounted $VOLUME_NAME at $MOUNTPOINT"
done
# ---------------------------