#!/usr/bin/env bash
source "$(dirname -- "${BASH_SOURCE[0]}")/lib.sh"
[[ $# == 1 ]] || die 'Usage: tools/rootfs-runtime-check ROOT'
root=$(realpath -e -- "$1")
[[ -s $root/usr/share/licenses/fds-cli/RUST-NOTICES.txt ]] || die 'Missing Rust dependency license notices'
"$FDS_ROOT/tools/verify-elf" "$root/usr/bin/ls" aarch64 glibc
"$FDS_ROOT/tools/verify-elf" "$root/usr/bin/xbps-query" aarch64 glibc
"$FDS_ROOT/tools/verify-elf" "$root/usr/bin/dasungd" aarch64 static
"$FDS_ROOT/tools/verify-elf" "$root/usr/bin/fds" aarch64 static
"$FDS_ROOT/tools/verify-elf" "$root/usr/bin/fds-boottrace" aarch64 static
"$FDS_ROOT/tools/verify-elf" "$root/usr/bin/fds-cartridged" aarch64 static
"$FDS_ROOT/tools/verify-elf" "$root/usr/bin/fds-profile" aarch64 static
for binary in fds-control fds-program fds-burn fds-inspect fds-eject fds-power fds-release; do
    "$FDS_ROOT/tools/verify-elf" "$root/usr/bin/$binary" aarch64 static
done
"$FDS_ROOT/tools/in-rootfs" "$root" --direct /usr/bin/xbps-pkgdb -a
log=$(mktemp "$FDS_ROOT/out/rootfs-runtime.XXXXXX")
trap 'rm -f "$log"' EXIT
"$FDS_ROOT/tools/in-rootfs" "$root" /bin/bash -euc '
    getconf GNU_LIBC_VERSION | grep -Eq "^glibc [0-9]"
    ls --version | grep -q "GNU coreutils"
    readelf --version | grep -q "GNU readelf"
    printf "ARM shell pipeline works\n" | gzip | gzip -d | grep -qx "ARM shell pipeline works"
    LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 locale charmap | grep -qx UTF-8
    xbps-query -p architecture fds-base | grep -qx aarch64
    dasungd --config /etc/dasungd.toml check
    fds --json info | grep -q aarch64
    fds-cartridged --help | grep -q SYSFS_ROOT
    fds-release --version | grep -qx "fds-release 0.1.0"
    s6-rc-db -c /etc/s6-rc/compiled list all | grep -qx cartridged
    s6-rc-db -c /etc/s6-rc/compiled list all | grep -qx dasungd
    s6-rc-db -c /etc/s6-rc/compiled list all | grep -qx test-echo
    printf "PASS: ARM glibc, GNU tools, shell pipelines, locale, XBPS and Dasung config under QEMU\n"
' | tee "$log"
# PRoot has returned zero after an internal abort on this host. Require the
# child's final acknowledgement as well as a successful process exit status.
grep -qx 'PASS: ARM glibc, GNU tools, shell pipelines, locale, XBPS and Dasung config under QEMU' "$log" || \
    die 'ARM runtime checker did not complete; inspect emulation output'
