#!/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"
fallback="$root/fallback"
mkdir -p "$workspace" "$fallback"
chmod 0500 "$workspace"

out="$(cd "$workspace" && TMPDIR="$fallback" XDG_CACHE_HOME="$fallback" "$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 "$fallback/tmpjail-*/tmp/.tmpjail" > /dev/null; then
  echo "expected the jail upper dir under the fallback root" >&2
  exit 1
fi

writable="$root/writable"
mkdir -p "$writable"
(cd "$writable" && TMPDIR="$fallback" "$tmpjail" bash -c 'echo hi > /tmp/marker') > /dev/null

if [[ ! -f "$writable/tmp/marker" ]]; then
  echo "expected a writable cwd to keep jailing into ./tmp" >&2
  exit 1
fi

echo "ok"
