#!/usr/bin/env bash
set -euo pipefail
# Run after: python3 prepare.py OUTPUT_ROOT
# Usage: bash run.sh CHECKOUT OUTPUT_ROOT before|after missing|configured|discoverable|session-file
checkout=$(realpath "$1")
output=$(realpath "$2")
side=$3
mode=$4
script_dir=$(cd -- "$(dirname -- "$0")" && pwd)
node_runtime=$(node -p 'process.execPath')
uid=$(id -u)
gid=$(id -g)
sudo -n unshare --mount --pid --fork --mount-proc --propagation private sh -c '
 mount -t tmpfs tmpfs /run/user
 # Exclude the unrelated installed GitLab CLI, which also autolaunches a bus.
 if [ -f /usr/bin/glab ]; then mount --bind /dev/null /usr/bin/glab; fi
 mkdir /run/user/"$1"
 chown "$1:$2" /run/user/"$1"
 exec setpriv --reuid="$1" --regid="$2" --init-groups "$3" "$4/driver.mjs" "$5" "$6/$7" "$7" "$8"
' sh "$uid" "$gid" "$node_runtime" "$script_dir" "$checkout" "$output" "$side" "$mode"
