#!/bin/sh
set -eu

script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
output_dir=${1:?usage: prepare_directory_fixtures.sh OUTPUT-DIRECTORY}

for tool in mkfs.erofs fsck.erofs dump.erofs python3; do
	command -v "$tool" >/dev/null 2>&1 || {
		echo "missing tool: $tool" >&2
		exit 1
	}
done
test ! -e "$output_dir" || {
	echo "output already exists: $output_dir" >&2
	exit 1
}

work_dir=$(mktemp -d "${TMPDIR:-/tmp}/repo22-directory.XXXXXX")
trap 'rm -rf "$work_dir"' EXIT HUP INT TERM
source_dir="$work_dir/source"
mkdir -p "$source_dir/alpha/bravo/charlie" \
	"$source_dir/alpha/sibling" "$source_dir/wide"

printf 'cold nested lookup payload\n' \
	> "$source_dir/alpha/bravo/charlie/payload.txt"
printf 'repeat lookup payload\n' > "$source_dir/alpha/bravo/repeat.txt"
printf 'sibling marker\n' > "$source_dir/alpha/sibling/marker.txt"
: > "$work_dir/expected-wide.txt"
index=0
while [ "$index" -lt 320 ]; do
	name=$(printf 'entry-%03d-abcdefghijklmnopqrstuvwxyz.txt' "$index")
	printf 'wide entry %03d\n' "$index" > "$source_dir/wide/$name"
	printf '%s\n' "$name" >> "$work_dir/expected-wide.txt"
	index=$((index + 1))
done
find "$source_dir" -exec touch -h -t 197001010000.00 {} +

mkfs.erofs --quiet -d0 -x-1 -T0 --all-time --all-root --workers=1 \
	-U 11111111-2222-3333-4444-555555555554 \
	"$work_dir/namei-base.erofs" "$source_dir"
python3 "$script_dir/erofs_fixture.py" make-directory-fixtures \
	--base "$work_dir/namei-base.erofs" --output "$output_dir"
cp -R "$source_dir" "$output_dir/source"
cp "$work_dir/expected-wide.txt" "$output_dir/expected-wide.txt"

fsck.erofs -d1 "$output_dir/namei-padding-nonzero.erofs"
dump.erofs --cat \
	--path=/wide/entry-079-abcdefghijklmnopqrstuvwxyz.txt \
	"$output_dir/namei-padding-nonzero.erofs" \
	> "$output_dir/padding-file.txt"
cmp "$source_dir/wide/entry-079-abcdefghijklmnopqrstuvwxyz.txt" \
	"$output_dir/padding-file.txt"
cat "$output_dir/fixture-evidence.txt"
cat "$output_dir/SHA256SUMS"
