#!/bin/sh
# DF-3082 fix-run (guest, PATCHED kernel): same image, same unprivileged
# user. Expected: every touch grows the entry count (no collapse), the
# vanish-list is empty, stats of existing names succeed, guest survives.
cd /mnt/e2/d || exit 1
ls | sort > /tmp/before_fix.txt
echo "entries before: $(wc -l < /tmp/before_fix.txt)"
for i in $(seq -w 1 50); do rm -f payloadname$i; done
echo "entries after rm loop: $(ls | wc -l)"
n=0; collapsed=0
while [ $n -lt 40 ]; do
	n=$((n+1))
	name=$(printf 'zzq%03d' $n)
	touch "$name" || echo "touch $name: $?"
	c=$(ls | wc -l)
	if [ $((n % 5)) -eq 1 ]; then echo "after touch $name: entries=$c"; fi
	if [ "$c" -lt 100 ]; then collapsed=1; echo "COLLAPSE at $name: $c"; break; fi
done
ls | sort > /tmp/after_fix.txt
echo "entries after 40 touches: $(wc -l < /tmp/after_fix.txt)"
comm -23 /tmp/before_fix.txt /tmp/after_fix.txt > /tmp/lost_fix.txt
echo "vanished pre-existing entries: $(wc -l < /tmp/lost_fix.txt)"
if [ "$collapsed" -eq 0 ] && [ ! -s /tmp/lost_fix.txt ]; then
	echo "FIX-OK: no truncate, no data loss"
fi
# lookup stress over surviving indexed entries: must not panic
ok=0; bad=0
for f in $(ls | grep payloadname | head -40); do
	if stat "/mnt/e2/d/$f" >/dev/null 2>&1; then ok=$((ok+1)); else bad=$((bad+1)); fi
done
echo "stat sweep: ok=$ok notfound=$bad (no panic = fix holds)"
