#!/bin/sh
# Rebuilds terminal/image/ from Fabrice Bellard's TinyEMU riscv64 Linux disk image and
# applies our changes:
#   - BusyBox: Bellard's 2017 build (1.21.1, dynamic, glibc 2.24.90 snapshot) is replaced by
#     ours, 1.37.0 linked statically against musl (tools/build_busybox.sh, run it first). The
#     applet symlinks are regenerated from its busybox.links and /lib (glibc) is emptied.
#   - /sbin/init (shell-exit report, /usr/share/ps-ef mount, sync root; see tools/init).
#   - /usr/bin/reinstall (see tools/reinstall).
#   - The kernel: ours from tools/build_kernel.sh (run it first), built from the source pinned in
#     terminal/image/LICENSES.txt. Without out/kernel-riscv64.bin this falls back to Bellard's
#     prebuilt one and says so; never ship that, because its source cannot be shown to match.
# The boot loader (riscv-pk, BSD) is copied unchanged.
#
# Rebuilding changes the image CRC, which makes every slot's saved guest disk stale; treat it
# as a save migration. The storyline (terminal/story/) is served over /usr/share/ps-ef at run time, so
# story edits never need a rebuild.
#
# Needs curl, tar, sha256sum and debugfs (e2fsprogs). On Windows run it from WSL:
#   wsl -d Debian -- sh terminal/tools/build_rootfs.sh
set -eu
here=$(cd "$(dirname "$0")" && pwd)
out="$here/../image"
url=https://bellard.org/tinyemu/diskimage-linux-riscv-2018-09-23.tar.gz
sha256=808ecc1b32efdd76103172129b77b46002a616dff2270664207c291e4fde9e14
bb="$here/out/busybox"
links="$here/out/busybox.links"
sbin() { command -v "$1" || echo "/usr/sbin/$1"; }
debugfs=$(sbin debugfs)
e2fsck=$(sbin e2fsck)
dumpe2fs=$(sbin dumpe2fs)
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT

if [ ! -f "$bb" ] || [ ! -f "$links" ]; then
  echo "build_rootfs.sh: $bb missing; run tools/build_busybox.sh first" >&2
  exit 1
fi

curl -sSfL "$url" -o "$tmp/img.tar.gz"
echo "$sha256  $tmp/img.tar.gz" | sha256sum -c -
tar -xzf "$tmp/img.tar.gz" -C "$tmp"
src="$tmp/diskimage-linux-riscv-2018-09-23"

cp "$src/root-riscv64.bin" "$tmp/root.bin"
tr -d '\r' < "$here/init" > "$tmp/init"
tr -d '\r' < "$here/reinstall" > "$tmp/reinstall"

# Read Bellard's tree to find what to remove: every symlink into busybox, and everything in /lib
# (glibc and its loader, which only his dynamic busybox used).
rootdir="$tmp/rootfs"
mkdir "$rootdir"
"$debugfs" -R "rdump / $rootdir" "$tmp/root.bin" 2>/dev/null
cmds="$tmp/cmds"
: > "$cmds"
for d in bin sbin usr/bin usr/sbin; do
  for f in "$rootdir/$d"/*; do
    if [ -L "$f" ] && case "$(readlink "$f")" in *busybox) true ;; *) false ;; esac; then
      echo "rm /$d/$(basename "$f")" >> "$cmds"
    fi
  done
done
for f in "$rootdir/lib"/*; do
  [ -e "$f" ] || [ -L "$f" ] || continue
  echo "rm /lib/$(basename "$f")" >> "$cmds"
done

# The new binary, owned by root.
cat >> "$cmds" <<CMDS
rm /bin/busybox
write $bb /bin/busybox
sif /bin/busybox mode 0100755
sif /bin/busybox uid 0
sif /bin/busybox gid 0
rm /sbin/init
write $tmp/init /sbin/init
sif /sbin/init mode 0100755
sif /sbin/init uid 0
sif /sbin/init gid 0
write $tmp/reinstall /usr/bin/reinstall
sif /usr/bin/reinstall mode 0100755
sif /usr/bin/reinstall uid 0
sif /usr/bin/reinstall gid 0
CMDS

# One relative symlink per applet, as `make install` lays them out. Skip /sbin/init (ours),
# /usr/bin/reinstall (ours) and /linuxrc (initrd only).
while read -r path; do
  case "$path" in
    /sbin/init|/usr/bin/reinstall|/linuxrc|/bin/busybox) continue ;;
    /bin/*|/sbin/*) target=../bin/busybox ;;
    /usr/bin/*|/usr/sbin/*) target=../../bin/busybox ;;
    *) echo "build_rootfs.sh: unexpected applet path $path" >&2; exit 1 ;;
  esac
  [ "${path%/*}" = /bin ] && target=busybox
  echo "symlink $path $target" >> "$cmds"
done < "$links"

"$debugfs" -w -f "$cmds" "$tmp/root.bin" > "$tmp/debugfs.log" 2>&1
if grep -iE 'error|cannot|not found|no such' "$tmp/debugfs.log"; then
  echo "build_rootfs.sh: debugfs reported the errors above" >&2
  exit 1
fi
# Bellard's files share one extended-attribute block, and debugfs `rm` does not drop its
# reference count. Let e2fsck fix that (exit 1 = errors corrected), then insist on a clean fs.
"$e2fsck" -fy "$tmp/root.bin" > "$tmp/fsck.log" 2>&1 || [ $? -eq 1 ] || { cat "$tmp/fsck.log"; exit 1; }
"$e2fsck" -fn "$tmp/root.bin" > "$tmp/fsck.log" 2>&1 || { cat "$tmp/fsck.log"; exit 1; }

mkdir -p "$out"
cp "$src/bbl64.bin" "$out/"
if [ -f "$here/out/kernel-riscv64.bin" ]; then
  cp "$here/out/kernel-riscv64.bin" "$out/"
else
  echo "build_rootfs.sh: WARNING: no out/kernel-riscv64.bin, using Bellard's prebuilt kernel" >&2
  cp "$src/kernel-riscv64.bin" "$out/"
fi
cp "$tmp/root.bin" "$out/root-riscv64.bin"
"$dumpe2fs" -h "$out/root-riscv64.bin" 2>/dev/null | grep -E '^Free (blocks|inodes):'
echo "wrote $out"
