#!/bin/sh
# debug1.sh — instrumented 6-round choreography (timestamps everywhere)
set -x
umount -f /df3173_mp 2>/dev/null
kldload autofs 2>/dev/null
sysctl vfs.autofs.timeout=1
sysctl vfs.autofs.retry_attempts=2
sysctl vfs.autofs.retry_delay=1
sysctl vfs.autofs.interruptible=1
sysctl vfs.autofs.cache=0
sysctl vfs.autofs.debug=0
mkdir -p /df3173_mp
mount_autofs -f df3173 "" /df3173_mp

: > /tmp/choreo.log
/root/poc/df3173/fake_daemon3173 1050 >/tmp/df3173_daemon.log 2>&1 &
DAEMON=$!

kldload /root/poc/df3173/df3173_race.ko
sleep 1
sysctl debug.df3173_mode=1

prev=0
end=$(( $(date +%s) + 40 ))
while [ $(date +%s) -lt $end ]; do
	r=$(sysctl -n debug.df3173_round)
	if [ "$r" -gt "$prev" ] 2>/dev/null; then
		prev=$r
		key=$(sysctl -n debug.df3173_key)
		echo "$(date +%s) round=$r spawn-creator" >> /tmp/choreo.log
		( stat /df3173_mp/$key; echo "$(date +%s) creator-rc=$?" >> /tmp/choreo.log ) >/dev/null 2>&1 &
		P=$!
		while [ "$(sysctl -n debug.df3173_stage)" -lt 1 ]; do
			sleep 0.02
		done
		echo "$(date +%s) round=$r spawn-releaser" >> /tmp/choreo.log
		( stat /df3173_mp/$key; echo "$(date +%s) releaser-rc=$?" >> /tmp/choreo.log ) >/dev/null 2>&1 &
		sleep 0.70
		echo "$(date +%s) round=$r kill-creator pid=$P" >> /tmp/choreo.log
		kill -9 $P 2>/dev/null
		wait $P 2>/dev/null
		echo "$(date +%s) round=$r creator-reaped" >> /tmp/choreo.log
	fi
	sleep 0.05
done
sleep 2
kill $DAEMON 2>/dev/null
cat /tmp/choreo.log
echo DEBUG1-DONE
