#!/bin/sh
# Builds the terminal guest's kernel: Linux 4.15 from riscv-linux commit a3b1e7a with the patch
# and config Fabrice Bellard published for his TinyEMU disk image, inside an Ubuntu 18.04 container
# (podman, else docker). build_rootfs.sh then puts it in terminal/image/. Building it ourselves is
# what makes the kernel's GPL source exact: Bellard's prebuilt binary came with a commit, a patch
# and a config, but nothing proves it was built from exactly those.
#
# Ubuntu 18.04's riscv64 cross toolchain (gcc 7.5, binutils 2.30) matches the one Bellard used
# (a gcc 7.3.1 prerelease), so the kernel builds unpatched. Newer ones do not: binutils 2.31
# breaks this kernel's vDSO link ("attempted static link of dynamic object", fixed upstream in
# 4.19), and 2.38+ rejects its CSR instructions.
#
# The source comes from git, not a GitHub archive download: fetching the pinned commit verifies
# every object against its hash, and `git archive | gzip -n` gives a byte-stable tarball, which
# is the one build_source_bundle.sh ships. GitHub's own archives are not guaranteed stable.
#
# Outputs, in terminal/tools/out/ (gitignored):
#   kernel-riscv64.bin   raw image (objcopy -O binary vmlinux), as TinyEMU loads it
#   kernel-src/          the source tarball, Bellard's patch and config, and this script's notes
#
# Work files live in $PSEF_KERNEL_WORK (default ~/.cache/psef-kernel). A build takes a few minutes.
set -eu
here=$(cd "$(dirname "$0")" && pwd)
repo=$(cd "$here/../.." && pwd)
work=${PSEF_KERNEL_WORK:-$HOME/.cache/psef-kernel}
commit=a3b1e7acc6a181e04e9a943942084395df4498dd
git_url=https://github.com/riscvarchive/riscv-linux
img_url=https://bellard.org/tinyemu/diskimage-linux-riscv-2018-09-23.tar.gz
img_sha256=808ecc1b32efdd76103172129b77b46002a616dff2270664207c291e4fde9e14
image=docker.io/library/ubuntu:18.04

if command -v podman >/dev/null 2>&1; then
  engine=podman
  owner=""  # rootless podman: container root is the host user already
elif command -v docker >/dev/null 2>&1; then
  engine=docker
  owner="$(id -u):$(id -g)"  # rootful docker: hand the outputs back to the caller
else
  echo "build_kernel.sh: needs podman or docker" >&2
  exit 1
fi

mkdir -p "$work" "$here/out"
img="$work/diskimage-linux-riscv-2018-09-23.tar.gz"
if [ ! -f "$img" ]; then
  curl -sSfL "$img_url" -o "$img.part"
  mv "$img.part" "$img"
fi
echo "$img_sha256  $img" | sha256sum -c -

# Fixed build identity, so two builds of this script give the same bytes.
"$engine" run --rm -v "$work:/w:Z" -v "$repo:/src:Z" \
  -e DEBIAN_FRONTEND=noninteractive -e COMMIT="$commit" -e GIT_URL="$git_url" -e OWNER="$owner" \
  -e KBUILD_BUILD_TIMESTAMP="Thu Sep 13 20:03:10 CEST 2018" -e KBUILD_BUILD_USER=ps-ef \
  -e KBUILD_BUILD_HOST=ps-ef -e KBUILD_BUILD_VERSION=1 -e SOURCE_DATE_EPOCH=1536861790 \
  "$image" sh -euc '
  apt-get update -qq
  apt-get install -y -qq build-essential bc bison flex git ca-certificates \
    gcc-riscv64-linux-gnu binutils-riscv64-linux-gnu >/dev/null
  cd /w
  if [ ! -f "riscv-linux-$COMMIT.tar.gz" ]; then
    rm -rf git && git init -q git
    git -C git fetch -q --depth 1 "$GIT_URL" "$COMMIT"
    [ "$(git -C git rev-parse FETCH_HEAD)" = "$COMMIT" ]
    git -C git archive --format=tar --prefix="riscv-linux-$COMMIT/" "$COMMIT" \
      | gzip -n -9 > "riscv-linux-$COMMIT.tar.gz.part"
    mv "riscv-linux-$COMMIT.tar.gz.part" "riscv-linux-$COMMIT.tar.gz"
    rm -rf git
  fi
  rm -rf img build && mkdir img build
  tar -xzf diskimage-linux-riscv-2018-09-23.tar.gz -C img
  p=img/diskimage-linux-riscv-2018-09-23/patches
  tar -xzf "riscv-linux-$COMMIT.tar.gz" -C build
  cd "build/riscv-linux-$COMMIT"
  patch -p1 < "/w/$p/riscv-linux.diff"
  cp "/w/$p/config_linux_riscv64" .config
  k="make ARCH=riscv CROSS_COMPILE=riscv64-linux-gnu- -j$(nproc)"
  $k olddefconfig
  # olddefconfig must not have changed anything, or this is not the config Bellard published.
  diff -u "/w/$p/config_linux_riscv64" .config | grep "^[-+]CONFIG" && { echo "config drifted" >&2; exit 1; } || true
  $k vmlinux
  riscv64-linux-gnu-objcopy -O binary vmlinux /w/kernel-riscv64.bin
  out=/src/terminal/tools/out
  rm -rf "$out/kernel-src" && mkdir -p "$out/kernel-src"
  cp /w/kernel-riscv64.bin "$out/kernel-riscv64.bin"
  cp "/w/riscv-linux-$COMMIT.tar.gz" "/w/$p/riscv-linux.diff" "/w/$p/config_linux_riscv64" \
    "/w/$p/readme.txt" "$out/kernel-src/"
  riscv64-linux-gnu-gcc --version | head -1 > "$out/kernel-src/toolchain.txt"
  riscv64-linux-gnu-ld --version | head -1 >> "$out/kernel-src/toolchain.txt"
  echo "container: ubuntu:18.04, packages gcc-riscv64-linux-gnu binutils-riscv64-linux-gnu" >> "$out/kernel-src/toolchain.txt"
  [ -z "$OWNER" ] || chown -R "$OWNER" "$out" /w
'

sha256sum "$here/out/kernel-riscv64.bin"
strings "$here/out/kernel-riscv64.bin" | grep -m1 "Linux version" || true
echo "wrote $here/out"
