#!/usr/bin/env bash
# Host-side driver, run as root on the existing research host. Unpacks the official,
# checksum-verified Ubuntu 24.04 cloud-image root filesystem and runs in-chroot.sh inside
# private mount and PID namespaces. The host's own /opt/felisyn runtime is not used or changed.
set -euo pipefail
BASE=/srv/felisyn-rehearsal-008
cd "$BASE"
log() { printf '%s %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*"; }

INDEX=https://cloud-images.ubuntu.com/releases/noble/
FILE=ubuntu-24.04-server-cloudimg-amd64-root.tar.xz
SERIAL=$(curl -fsSL "$INDEX" | grep -o 'release-[0-9]\{8\}\(\.[0-9]\{1,\}\)\{0,1\}/' | sort -u | tail -n 1 | tr -d /)
log "cloud image $INDEX$SERIAL/$FILE"
for f in SHA256SUMS SHA256SUMS.gpg "$FILE"; do curl -fsSL --retry 2 -o "$f" "$INDEX$SERIAL/$f"; done
KEYRING=/usr/share/keyrings/ubuntu-cloudimage-keyring.gpg
if [ -f "$KEYRING" ]; then
  gpgv --keyring "$KEYRING" SHA256SUMS.gpg SHA256SUMS
  log "SHA256SUMS signature verified with $KEYRING"
else
  log "cloud-image keyring absent; SHA256SUMS signature NOT verified"
fi
grep -E " \*?$FILE\$" SHA256SUMS | sha256sum -c -
printf '{"serial":"%s","file":"%s","sha256":"%s"}\n' "$SERIAL" "$FILE" "$(sha256sum "$FILE" | cut -d' ' -f1)" > image.json

mkdir rootfs
tar -C rootfs --numeric-owner -xpJf "$FILE"
# A chroot has no systemd-resolved; give it the host's upstream resolvers instead of the stub link.
rm -f rootfs/etc/resolv.conf
cp /run/systemd/resolve/resolv.conf rootfs/etc/resolv.conf
cp -a kit/execution-003 rootfs/tmp/felisyn-reproduction
cp -a kit/protocol-006 rootfs/tmp/protocol-006
install -m 755 kit/in-chroot.sh rootfs/tmp/in-chroot.sh

log "starting isolated rehearsal"
set +e
unshare --mount --pid --fork --propagation private /bin/bash -c '
set -e
R=/srv/felisyn-rehearsal-008/rootfs
mount -t proc proc "$R/proc"
mount --rbind /sys "$R/sys"
mount --rbind /dev "$R/dev"
exec chroot "$R" /usr/bin/env -i HOME=/root LANG=C.UTF-8 TERM=dumb \
  PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin /bin/bash /tmp/in-chroot.sh
'
code=$?
set -e
log "rehearsal exit $code"
if findmnt -R "$BASE/rootfs" >/dev/null; then log "WARNING: mounts remain under rootfs"; else log "no host-visible mounts under rootfs"; fi
exit "$code"
