#!/bin/bash
# Secondary /dev/cuse identity control; runs in the same privileged fixture.
set -uo pipefail
WORK=/work; BIN=$WORK/bin; RESULTS=$WORK/results; PLATFORM=${PLATFORM:-systrap}; SECS=${CUSE_SECS:-5}
for role in vuln fixed; do
 race=/race-cuse-$role; root=/run/runsc-cuse-$role; bundle=/bundle-cuse-$role; ctr=cuse-$role
 rm -rf "$race" "$root" "$bundle"; mkdir -p "$race" "$root" "$bundle/rootfs"; mount -t tmpfs -o mode=1777 tmpfs "$race"
 cp "$BIN/guest_cuse_identity" "$bundle/rootfs/guest_cuse_identity"
 cat >"$bundle/config.json" <<EOF
{"ociVersion":"1.0.2","process":{"terminal":false,"user":{"uid":0,"gid":0},"args":["/guest_cuse_identity","/race/target","$SECS"],"env":["PATH=/"],"cwd":"/"},"root":{"path":"rootfs","readonly":false},"mounts":[{"destination":"/proc","type":"proc","source":"proc"},{"destination":"/dev","type":"tmpfs","source":"tmpfs"},{"destination":"/race","type":"bind","source":"$race","options":["rbind","rw"]}],"linux":{"namespaces":[{"type":"pid"},{"type":"network"},{"type":"ipc"},{"type":"uts"},{"type":"mount"}]}}
EOF
 "$BIN/host_cuse_swapper" "$race" $((SECS+5)) >"$RESULTS/cuse-swapper-$role.log" 2>&1 & sw=$!
 timeout --signal=KILL $((SECS+15)) "$BIN/runsc-$role" --root "$root" --sidecar-usage-policy=LEGACY_DEPRECATED_SLOW_EMBEDDED_FALLBACK --directfs=true --platform="$PLATFORM" --network=none --ignore-cgroups run --bundle "$bundle" "$ctr" >"$RESULTS/cuse-guest-$role.log" 2>&1 || true
 kill "$sw" 2>/dev/null || true; wait "$sw" 2>/dev/null || true; "$BIN/runsc-$role" --root "$root" delete --force "$ctr" >/dev/null 2>&1 || true; umount "$race" || true
 echo "CUSE role=$role: $(tail -1 "$RESULTS/cuse-guest-$role.log")"
done
