#!/bin/bash
# Read-only diagnostic collection, intended to run on the FDS target.
set -euo pipefail
umask 077
if [[ $# != 1 || $1 != /* ]]; then
    printf 'Usage: bash capture-hardware /absolute/new/capture-directory\n' >&2
    exit 2
fi
output=$1
mkdir -- "$output"
output=$(realpath -- "$output")
trap 'printf "Capture interrupted; partial files retained in %s\n" "$output" >&2' INT TERM
printf 'format=1\ncreated_utc=%s\nuid=%s\n' "$(date -u +%FT%TZ)" "$(id -u)" >"$output/capture.txt"
printf 'command\texit_status\n' >"$output/status.tsv"
collect() {
    local name=$1 status=0
    shift
    "$@" >"$output/$name.txt" 2>"$output/$name.stderr.txt" || status=$?
    printf '%s\t%s\n' "$name" "$status" >>"$output/status.tsv"
}
collect identity fds --json info
collect bays fds --json bays
collect topology fds --json topology
collect profiles fds --json profiles
collect power fds --json power status
collect boot-profile fds --json boot-profile
collect kernel uname -a
collect cmdline cat /proc/cmdline
collect kernel-log dmesg --time-format=raw
collect usb-tree lsusb -t
collect usb-devices lsusb
collect block-devices lsblk --json -o NAME,MAJ:MIN,MODEL,SERIAL,SIZE,RO,TYPE,FSTYPE,PARTLABEL,MOUNTPOINTS
collect mounts cat /proc/self/mountinfo
collect interfaces ip -details link
collect memory cat /proc/meminfo
collect os-release cat /etc/os-release
collect package-list xbps-query -l
(
    cd -- "$output"
    sha256sum -- ./*.txt status.tsv >SHA256SUMS
)
printf 'Collected diagnostics in %s\nRead status.tsv for unavailable or failed commands; this capture is not a hardware pass.\n' "$output"
