#!/bin/bash
## Roundtrip, for both sigil dialects: export is regeneration-stable,
## verify passes, and import into a fresh clone of upstream reproduces the
## exact branch tips, fsck-clean.
set -euo pipefail
cd "$(dirname "$0")"
source ./lib.sh

work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT

make_corpus "$work/corpus"
source "$work/corpus/FACTS"

for sigil in quote tab; do
	p="$work/$sigil"

	"$PATCHETTE" export "--sigil=$sigil" "$work/corpus/dev" "$p/patches" "$base" topic/fancy docs-polish >/dev/null
	"$PATCHETTE" export "--sigil=$sigil" "$work/corpus/dev" "$p/again" "$base" topic/fancy docs-polish >/dev/null
	if diff -r "$p/patches" "$p/again" >/dev/null; then
		pass "$sigil: export is regeneration-stable (two runs byte-identical)"
	else
		fail "$sigil: export is not regeneration-stable"
	fi

	# Guard the guard: confirm the flag actually switched the emitted framing,
	# or this loop would just test the quote dialect twice.
	sample="$p/patches/topic¦fancy/teach-gizmo-to-hum.patch"
	case $sigil in
	quote) want=$'> The hum is load-bearing.' ;;
	tab) want=$'\tThe hum is load-bearing.' ;;
	esac
	if grep -qxF "$want" "$sample"; then
		pass "$sigil: emitted message framing matches the dialect"
	else
		fail "$sigil: emitted message framing does not match the dialect"
	fi

	if "$PATCHETTE" verify "$work/corpus/dev" "$p/patches" >/dev/null; then
		pass "$sigil: verify passes on a fresh export"
	else
		fail "$sigil: verify rejected a fresh export"
	fi

	# The recreate story: upstream has none of our branches; the patches repo
	# alone must bring them back, byte-exact.
	git clone -q "$work/corpus/upstream" "$p/fresh"
	"$PATCHETTE" import "$p/fresh" "$p/patches" >/dev/null
	got_fancy=$(git -C "$p/fresh" rev-parse refs/heads/topic/fancy)
	got_docs=$(git -C "$p/fresh" rev-parse refs/heads/docs-polish)
	if [[ $got_fancy == "$tip_topic_fancy" && $got_docs == "$tip_docs_polish" ]]; then
		pass "$sigil: import reproduces exact tips"
	else
		fail "$sigil: import tips differ: topic/fancy $got_fancy (want $tip_topic_fancy), docs-polish $got_docs (want $tip_docs_polish)"
	fi

	if git -C "$p/fresh" fsck --strict >/dev/null 2>&1; then
		pass "$sigil: fsck --strict clean on the replayed repo"
	else
		fail "$sigil: fsck --strict rejected the replayed repo"
	fi
done

exit "$RESULT"
