#!/usr/bin/env bash
set -euo pipefail

here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
tmpjail="$here/../bin/tmpjail"

root="$(mktemp -d "${XDG_CACHE_HOME:-$HOME/.cache}/tmpjail-readonly-test-XXXXXX")"
trap 'chmod -R u+w "$root" 2>/dev/null || true; rm -rf "$root"' EXIT

workspace="$root/workspace"
cache="$root/cache"
mkdir -p "$workspace" "$cache"
chmod 0500 "$workspace"

out="$(cd "$workspace" && TMPDIR="$cache" XDG_CACHE_HOME="$cache" "$tmpjail" \
  bash -c 'printf "%s|%s\n" "$TMPDIR" "$(mktemp -p /tmp jailedXXXX && echo ok)"')"

case "$out" in
  /tmp\|*) ;;
  *) echo "expected /tmp to stay jailed under a read-only cwd, got: $out" >&2; exit 1 ;;
esac

if [[ -e "$workspace/tmp" ]]; then
  echo "tmpjail wrote into the read-only workspace" >&2
  exit 1
fi

if ! compgen -G "$cache/agent-tmp/tmpjail/*/tmp/.tmpjail" > /dev/null; then
  echo "expected the jail upper dir under the cache root" >&2
  exit 1
fi

writable="$root/writable"
mkdir -p "$writable/nested"
/usr/bin/git -C "$writable" init -q
(cd "$writable" && TMPDIR="$cache" XDG_CACHE_HOME="$cache" "$tmpjail" \
  bash -c 'echo hi > /tmp/marker') > /dev/null

if [[ -e "$writable/tmp" ]]; then
  echo "tmpjail wrote into a writable cwd instead of the cache" >&2
  exit 1
fi

seen="$(cd "$writable/nested" && TMPDIR="$cache" XDG_CACHE_HOME="$cache" "$tmpjail" \
  bash -c 'cat /tmp/marker 2>/dev/null || echo MISSING')"

if [[ "$seen" != "hi" ]]; then
  echo "a cd within one tree swapped /tmp: expected 'hi', got '$seen'" >&2
  exit 1
fi

echo "ok"
