#!/bin/sh
# Read-only target selection for the live installer and Debian Installer.
set -eu
export LC_ALL=C
PATH=/usr/sbin:/usr/bin:/sbin:/bin
export PATH
SYS=/sys
PROC=/proc
DEV=/dev
TMP=/run

die() { printf '%s\n' "$*" >&2; exit 1; }
is_block() { [ -b "$1" ]; }
check_devnum() {
    # Debian Installer does not ship stat. Both its BusyBox ls and GNU ls
    # show block numbers as two numeric fields ("8, 0") with -lnL.
    actual=$(ls -lnL "$1" | awk '{gsub(/,/, "", $5); print $5 ":" $6}')
    [ "$actual" = "$2" ]
}
number() { case $1 in ''|*[!0-9]*) return 1;; esac; }
node_name() { case $1 in ''|*[!a-zA-Z0-9_.:-]*) return 1;; esac; }
attr() { [ -r "$1" ] || die "Cannot read disk metadata: $1"; cat "$1"; }
model_of() {
    for candidate in "$1/device/model" "$1/model" "$1/device/name" "$1/serial" "$1/device/serial"; do
        if [ -r "$candidate" ]; then
            sed -n '1{s/[^A-Za-z0-9 ._()+:-]/?/g;s/^ *//;s/ *$//;p;}' "$candidate" | head -c 80
            return
        fi
    done
    printf '%s' "${1##*/}"
}

edition=
prove=no
while [ "$#" -gt 0 ]; do
    case $1 in
        --edition) [ "$#" -gt 1 ] || die "Missing edition"; edition=$2; shift 2 ;;
        --prove-empty) prove=yes; shift ;;
        *) break ;;
    esac
done
[ -n "$edition" ] || edition=$(uname -m)
case $edition in
    amd64|x86_64) min_sectors=52428800 ;; # 25 GiB
    i386|i486|i586|i686) min_sectors=20971520 ;; # 10 GiB
    *) die "Unsupported installer architecture" ;;
esac
op=${1:-inspect}
[ "$#" -eq 0 ] || shift
token_arg=
erase=no
case $op in
    inspect|select|token|describe) [ "$#" -eq 0 ] || die "Unexpected arguments" ;;
    check|check-token)
        [ "$#" -ge 1 ] || die "Missing previously displayed target token"
        token_arg=$1; shift
        [ "${#token_arg}" -eq 64 ] || die "Invalid target token"
        case $token_arg in *[!a-f0-9]*) die "Invalid target token";; esac
        if [ "$#" -eq 1 ] && [ "$1" = --erase ]; then erase=yes; shift; fi
        [ "$#" -eq 0 ] || die "Unexpected authorization arguments"
        ;;
    *) die "Unknown target operation" ;;
esac
umask 077
work=$(mktemp -d "$TMP/newworld-disk.XXXXXX") || die "Cannot create a private probe directory"
trap 'rm -rf "$work"' EXIT
trap 'exit 1' HUP INT TERM
[ -d "$SYS/class/block" ] && [ -d "$SYS/dev/block" ] || die "Linux block topology unavailable"
[ -s "$PROC/self/mountinfo" ] || [ -r "$PROC/self/mountinfo" ] || die "Mount information unavailable"
[ -r "$PROC/swaps" ] || die "Swap information unavailable"
[ -r "$PROC/sys/kernel/random/boot_id" ] || die "Boot identity unavailable"
boot=$(cat "$PROC/sys/kernel/random/boot_id")
[ -n "$boot" ] || die "Boot identity is empty"
for tool in blkid dd sha256sum awk readlink sort cmp head wc; do
    command -v "$tool" >/dev/null 2>&1 || die "Required disk probe unavailable: $tool"
done

# Map a mounted /dev/block major:minor back to all whole disks. Mapper/MD mounts
# recurse into all slaves. A live image backed by an unresolved loop is unsafe.
media_roots() (
    node=$1
    depth=$2
    [ "$depth" -lt 12 ] || die "Installer media block ancestry is cyclic"
    node_name "$node" && [ -e "$SYS/class/block/$node" ] || die "Unknown installer media device"
    bp=$(readlink -f "$SYS/class/block/$node") || die "Cannot resolve installer media device"
    if [ -f "$bp/partition" ]; then
        parent=${bp%/*}
        media_roots "${parent##*/}" "$((depth+1))"
        exit
    fi
    case $node in loop*|nbd*|rbd*) die "Installer media backing cannot be safely mapped to a physical disk";; esac
    [ -d "$bp/slaves" ] || die "Installer media has no readable dependency information"
    has=no
    for slave in "$bp"/slaves/*; do
        [ -e "$slave" ] || continue
        has=yes
        media_roots "${slave##*/}" "$((depth+1))" || exit 1
    done
    if [ "$has" = no ]; then
        case $node in dm-*|md[0-9]*) die "Installer media backing devices are unresolved";; esac
        printf '%s\n' "$node"
    fi
)

# Each result is internal, external, or unknown. Only positively identified
# fixed hardware is eligible. USB ancestry takes precedence over SCSI/NVMe.
transport() (
    name=$1; path=$2
    case $name in
        loop[0-9]*|ram[0-9]*|zram[0-9]*|dm-*|md[0-9]*|nbd[0-9]*|rbd[0-9]*|drbd[0-9]*|zd[0-9]*|bcache[0-9]*|sr[0-9]*|scd[0-9]*|fd[0-9]*|mtdblock*|mmcblk*boot[0-9]*|mmcblk*rpmb) echo external; exit ;;
    esac
    if [ -r "$path/device/type" ]; then
        case $(cat "$path/device/type") in 1|4|5|7|8|9|14|SD|SDIO) echo external; exit;; esac
    fi
    removable=$(attr "$path/removable")
    case $removable in 1) echo external; exit;; 0) :;; *) echo unknown; exit;; esac
    physical=no; pci=no; ata=no; virtio=no; sas=no; mmc=no; pci_nvme=no
    parent=$path
    while [ "$parent" != "$SYS" ] && [ "$parent" != / ] && [ -n "$parent" ]; do
        sub=
        if [ -L "$parent/subsystem" ]; then sub=$(readlink -f "$parent/subsystem") || exit 1; sub=${sub##*/}; fi
        part=${parent##*/}
        case $sub in
            usb|thunderbolt|firewire|iscsi_session|iscsi_connection|fc_transport|fc_remote_ports|fc_host|nvme-fabrics) echo external; exit ;;
            pci) pci=yes ;;
            ata_port|ata_link) ata=yes ;;
            virtio) virtio=yes ;;
            sas_device|sas_end_device|sas_port|sas_phy) sas=yes ;;
            mmc|mmc_host) mmc=yes ;;
            nvme)
                if [ -r "$parent/transport" ]; then
                    case $(cat "$parent/transport") in pcie) pci_nvme=yes;; *) echo external; exit;; esac
                fi ;;
        esac
        case $part in usb[0-9]*|iscsi_session*|session[0-9]*|rport-*|firewire*|thunderbolt*) echo external; exit;;
            ata[0-9]*|ide[0-9]*) ata=yes;;
        esac
        # Hot-pluggable PCI tunnels may appear as ordinary NVMe/SATA devices.
        if [ "$sub" = pci ]; then
            if [ -r "$parent/external_facing" ] && [ "$(cat "$parent/external_facing")" = 1 ]; then echo external; exit; fi
            if [ -r "$parent/removable" ]; then
                # "unknown" on a PCI host bridge describes its firmware slot,
                # not the physical transport of a positively identified fixed disk.
                case $(cat "$parent/removable") in removable|1) echo external; exit;; esac
            fi
        fi
        case $sub in pci|platform|virtio|mmc_host) physical=yes;; esac
        parent=${parent%/*}
    done
    case $name in
        sd[a-z]*|hd[a-z]*)
            tail=${name#??}
            case $tail in *[!a-z]*|'') echo unknown; exit;; esac
            if [ "$physical" = yes ] && { [ "$ata" = yes ] || [ "$virtio" = yes ] || [ "$sas" = yes ]; }; then echo internal; else echo unknown; fi ;;
        vd[a-z]*)
            tail=${name#vd}; case $tail in *[!a-z]*|'') echo unknown; exit;; esac
            if [ "$virtio" = yes ] && [ "$physical" = yes ]; then echo internal; else echo unknown; fi ;;
        nvme[0-9]*n[0-9]*)
            ids=${name#nvme}; ctrl=${ids%%n*}; ns=${ids#*n}
            if ! number "$ctrl" || ! number "$ns"; then echo unknown; exit; fi
            if [ "$pci_nvme" = yes ] && [ "$pci" = yes ]; then echo internal; else echo unknown; fi ;;
        mmcblk[0-9]*)
            tail=${name#mmcblk}; case $tail in *[!0-9]*|'') echo unknown; exit;; esac
            if [ "$mmc" = yes ] && [ -r "$path/device/type" ] && [ "$(cat "$path/device/type")" = MMC ]; then echo internal; else echo unknown; fi ;;
        *) echo unknown ;;
    esac
)

enumerate() (
    cat "$PROC/self/mountinfo" > "$work/mountinfo"
    [ -s "$work/mountinfo" ] || die "Mount information is empty"
    awk '$5=="/cdrom" || $5=="/run/live/medium" || $5=="/lib/live/mount/medium" || $5=="/run/initramfs/live" {print $3}' "$work/mountinfo" > "$work/media-numbers"
    [ -s "$work/media-numbers" ] || die "Cannot identify the mounted installer medium"
    : > "$work/media"
    while IFS= read -r num; do
        ref=$(readlink -f "$SYS/dev/block/$num") || die "Cannot resolve mounted installer medium"
        [ -e "$ref" ] || die "Installer medium is not backed by a known block device"
        media_roots "${ref##*/}" 0 >> "$work/media" || exit 1
    done < "$work/media-numbers"
    : > "$work/internals"
    for link in "$SYS"/class/block/*; do
        [ -e "$link" ] || continue
        path=$(readlink -f "$link") || die "Unstable block topology"
        [ ! -e "$path/partition" ] || continue
        name=${link##*/}; node_name "$name" || die "Unrecognized block name"
        if awk -v n="$name" '$0==n {found=1} END {exit !found}' "$work/media"; then continue; fi
        kind=$(transport "$name" "$path") || die "Cannot determine transport for $name"
        case $kind in external) continue;; internal) printf '%s\n' "$name" >> "$work/internals";; *) die "Cannot classify attached disk $name; disconnect it and retry";; esac
    done
    count=$(wc -l < "$work/internals")
    [ "$count" -eq 1 ] || die "Expected exactly one internal installation disk, found $count"
    cat "$work/internals"
)

assert_unused() (
    node=$1
    path=$SYS/class/block/$node
    [ "$(attr "$path/ro")" = 0 ] || die "Disk or partition $node is read-only"
    [ -d "$path/holders" ] && [ -r "$path/holders" ] || die "Cannot check active disk holders for $node"
    for holder in "$path"/holders/*; do
        [ ! -e "$holder" ] || die "Disk $node has an active storage holder"
    done
    devnum=$(attr "$path/dev")
    case $devnum in *:*) :;; *) die "Invalid device number for $node";; esac
    if awk -v d="$devnum" '$3==d {found=1} END {exit !found}' "$work/mountinfo"; then die "Disk $node is mounted"; fi
    # Kernel reports canonical swap paths in most cases. Resolve aliases too.
    awk 'NR>1 {print $1}' "$PROC/swaps" > "$work/swap-names"
    while IFS= read -r swap; do
        [ "$swap" != "$DEV/$node" ] || die "Disk $node is active swap"
        if [ -e "$swap" ] && [ "$(readlink -f "$swap")" = "$DEV/$node" ]; then die "Disk $node is active swap"; fi
    done < "$work/swap-names"
)

parts() (
    base=$1
    for entry in "$SYS/class/block/$base"/*; do
        if [ -f "$entry/partition" ]; then
            pn=${entry##*/}; node_name "$pn" || die "Invalid partition name"
            printf '%s\n' "$pn"
        fi
    done
)

probe_node() (
    node=$1; cls=$SYS/class/block/$node; dev=$DEV/$node
    assert_unused "$node"
    is_block "$dev" || die "Missing block device $dev"
    num=$(attr "$cls/dev")
    check_devnum "$dev" "$num" || die "Disk node $dev does not match the kernel device identity"
    [ "$(readlink -f "$SYS/dev/block/$num")" = "$(readlink -f "$cls")" ] || die "Inconsistent kernel device identity for $dev"
    total=$(attr "$cls/size"); number "$total" && [ "$total" -gt 0 ] || die "Invalid sector count for $node"
    printf 'node=%s\nnumber=%s\nsectors=%s\n' "$node" "$(attr "$cls/dev")" "$total"
    if [ -f "$cls/partition" ]; then
        printf 'partition=%s\nstart=%s\n' "$(attr "$cls/partition")" "$(attr "$cls/start")"
        : > "$work/occupied"
    fi
    status=0
    blkid -p -o export "$dev" > "$work/blkid-out" 2> "$work/blkid-err" || status=$?
    case $status in
        0)
            if awk -F= '$1=="TYPE" && ($2 ~ /(_raid_member|^LVM[12]_member|^zfs_member|^ceph_bluestore|^drbd|^bcache)$/) {f=1} END {exit !f}' "$work/blkid-out"; then
                die "$dev contains storage-pool membership; its other data devices cannot be safely identified"
            fi
            : > "$work/occupied"; sort "$work/blkid-out";;
        2) [ ! -s "$work/blkid-err" ] || die "Signature probe could not read $dev";;
        8) : > "$work/occupied"; echo 'signatures=ambiguous';;
        *) die "Signature probe failed for $dev (status $status)";;
    esac
    count=128; [ "$total" -ge "$count" ] || count=$total
    for offset in 0 "$(((total-count)/2))" "$((total-count))"; do
        dd if="$dev" of="$work/sample" bs=512 skip="$offset" count="$count" 2>/dev/null || die "I/O error on $dev"
        [ "$(wc -c < "$work/sample")" -eq "$((count*512))" ] || die "Short read on $dev"
        sum=$(sha256sum < "$work/sample"); printf 'sample %s %s\n' "$offset" "${sum%% *}"
        if [ ! -f "$work/occupied" ]; then
            dd if=/dev/zero of="$work/zeros" bs=512 count="$count" 2>/dev/null || die "Cannot construct comparison data"
            cmp -s "$work/sample" "$work/zeros" || : > "$work/occupied"
        fi
    done
)

name=$(enumerate) || exit 1
cls=$SYS/class/block/$name
sys_path=$(readlink -f "$cls") || die "Unstable disk path"
seq=$(attr "$cls/diskseq"); number "$seq" && [ "$seq" -gt 0 ] || die "Cannot establish disk generation"
sectors=$(attr "$cls/size"); number "$sectors" && [ "$sectors" -ge "$min_sectors" ] || die "The sole internal disk is too small for this edition"
bytes=$(awk -v s="$sectors" 'BEGIN {if(s>17592186044415)exit 1;printf "%.0f",s*512}') || die "Unsupported disk size"
model=$(model_of "$cls")
[ -n "$model" ] || model=$name
parts "$name" > "$work/parts"
{
    printf 'edition-min=%s\nboot=%s\npath=%s\ndiskseq=%s\nsize=%s\nmodel=%s\n' "$min_sectors" "$boot" "$sys_path" "$seq" "$sectors" "$model"
    for id in wwid serial device/wwid device/serial device/cid; do
        if [ -r "$cls/$id" ]; then printf '%s=' "$id"; cat "$cls/$id"; fi
    done
    probe_node "$name" || exit 1
    while IFS= read -r part; do probe_node "$part" || exit 1; done < "$work/parts"
} > "$work/fingerprint"
state=unverified
if [ -f "$work/occupied" ]; then
    state=occupied
elif [ "$prove" = yes ]; then
    # Normal inspection never reads a whole disk. A caller explicitly asking
    # for blank certification opts into a complete comparison on every check.
    # Use cmp's EOF comparison against an equally long zero stream. Check the
    # producer's exit independently, without relying on a non-POSIX pipefail.
    mknod "$work/zero-stream" p || die "Cannot prepare a bounded zero stream"
    (
        # count/length options in Debian Installer's 32-bit BusyBox head and
        # cmp can overflow at 4 GiB. Generate bounded blocks with 64-bit ash.
        left=$((sectors/2048))
        while [ "$left" -gt 0 ]; do
            step=$left; [ "$step" -le 2048 ] || step=2048
            dd if=/dev/zero bs=1048576 count="$step" 2>/dev/null || exit 1
            left=$((left-step))
        done
        dd if=/dev/zero bs=512 count="$((sectors%2048))" 2>/dev/null || exit 1
    ) > "$work/zero-stream" &
    producer=$!
    result=0; cmp -s "$DEV/$name" "$work/zero-stream" || result=$?
    prod_status=0; wait "$producer" || prod_status=$?
    case $result in
        0) [ "$prod_status" -eq 0 ] || die "Incomplete zero verification"; state=blank;;
        1) state=occupied;;
        *) die "I/O error during zero verification";;
    esac
fi
printf 'state=%s\n' "$state" >> "$work/fingerprint"
# Recheck topology/usage after the samples (or an explicitly requested long scan).
again=$(enumerate) || exit 1
[ "$again" = "$name" ] && [ "$(readlink -f "$cls")" = "$sys_path" ] && [ "$(attr "$cls/diskseq")" = "$seq" ] && [ "$(attr "$cls/size")" = "$sectors" ] || die "Disk identity changed during inspection"
parts "$name" > "$work/parts-after"
cmp -s "$work/parts" "$work/parts-after" || die "Partition topology changed during inspection"
assert_unused "$name"
while IFS= read -r part; do assert_unused "$part"; done < "$work/parts"
token=$(sha256sum < "$work/fingerprint"); token=${token%% *}
if [ -n "$token_arg" ]; then
    [ "$token" = "$token_arg" ] || die "The previously displayed disk has changed; inspect it again"
    if [ "$state" != blank ] && [ "$erase" != yes ]; then die "Explicit erase confirmation is required for this disk"; fi
fi
occupied=true; [ "$state" != blank ] || occupied=false
case $op in
    token) printf '%s\n' "$token" ;;
    select) [ "$state" = blank ] || die "Explicit erase confirmation is required"; printf '%s\n' "$DEV/$name" ;;
    check-token) printf '%s\n' "$DEV/$name" ;;
    describe) printf '%s\t%s\t%s\t%s\t%s\n' "$DEV/$name" "$token" "$bytes" "$state" "$model" ;;
    *) printf '{"path":"%s","token":"%s","display":"%s","model":"%s","size_bytes":%s,"occupied":%s,"state":"%s"}\n' "$DEV/$name" "$token" "$name" "$model" "$bytes" "$occupied" "$state" ;;
esac
