#!/bin/bash
# /tools/mount_hwmbw
# Find and mount filesystem with LABEL=SLKhwm_bw at /hwm_bw
# This is to mount the Hardware Model Bootware partition on the
# Raspberry Pi and any other HWM's that use this layout.

LABEL="SLKhwm_bw"
MOUNTPOINT="/hwm_bw"

mkdir -p "$MOUNTPOINT"

# udev-style symlink (preferred, simplest)
if [ -e "/dev/disk/by-label/$LABEL" ]; then
    mount "/dev/disk/by-label/$LABEL" "$MOUNTPOINT" && exit 0
fi

# Fallback: brute-force scan block devices
for dev in /dev/*; do
    case "$dev" in
        /dev/loop*|/dev/ram*|/dev/null|/dev/zero) continue ;;
    esac

    # Try mounting temporarily to read the label
    TMP="/tmp/hwm_scan"
    mkdir -p "$TMP"

    if mount -o ro "$dev" "$TMP" 2>/dev/null; then
        if [ -e "$TMP"/. ]; then
            # BusyBox-compatible label check
            if [ "$(blkid -s LABEL -o value "$dev" 2>/dev/null)" = "$LABEL" ]; then
                umount "$TMP"
                mount "$dev" "$MOUNTPOINT" && exit 0
            fi
        fi
        umount "$TMP"
    fi
done

echo "ERROR: Filesystem with LABEL=$LABEL not found" >&2
exit 1

