#!/bin/sh
# Read optional firmware and preseed data only from external installation media.
set -eu
mode=$1
device=$(readlink -f "$2")
case "$device" in /dev/*) ;; *) exit 1 ;; esac
[ -b "$device" ] || exit 1
name=${device##*/}
node=$(readlink -f "/sys/class/block/$name")
[ -d "$node" ] || exit 1
disk=$node
if [ -f "$node/partition" ]; then disk=${node%/*}; fi
case "$disk" in
    */usb[0-9]*/*) ;;
    *)
        removable=$(cat "$disk/removable" 2>/dev/null || true)
        optical=$(cat "$disk/device/type" 2>/dev/null || true)
        [ "$removable" = 1 ] || [ "$optical" = 5 ] || exit 1
        ;;
esac
case "$mode" in
    eligible) exit 0 ;;
    options) ;;
    *) exit 1 ;;
esac
# Mounting a whole partitioned disk would claim the sibling USB log volume.
if [ "$disk" = "$node" ]; then
    for child in "$node"/*; do [ ! -f "$child/partition" ] || exit 1; done
fi
label=$(blkid -p -s LABEL -o value "$device" 2>/dev/null || true)
[ "$label" != NWDEBUG ] || exit 1
kind=$(blkid -p -s TYPE -o value "$device" 2>/dev/null) || exit 1
opts=ro,nosuid,nodev,noexec
case "$kind" in
    ext3|ext4) opts=$opts,noload ;;
    xfs) opts=$opts,norecovery ;;
    btrfs) opts=$opts,nologreplay ;;
    iso9660|udf|vfat|msdos|ext2|exfat|ntfs) ;;
    *) exit 1 ;;
esac
printf '%s\n' "$opts"
