#!/bin/sh
# 2-CPU composition driver: fresh overlay each attempt, build once per boot,
# run until /tmp/df3017.root exists (uid=0 proof).
set -u
cd "$(dirname "$0")"

LOG=run2cpu.log
: > "$LOG"
attempt=0
KEY=id_ed25519_dfbsd
SSH="-F /dev/null -p 5535 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i $KEY"

while [ "$attempt" -lt 25 ]; do
	attempt=$((attempt + 1))
	echo "=== 2cpu attempt $attempt $(date -u +%H:%M:%S) ===" | tee -a "$LOG"

	# fresh guest
	kill $(cat /tmp/opencode/df3017-2cpu.pid 2>/dev/null) 2>/dev/null
	sleep 2
	ps ax | grep "df3017-2cpu.qcow2" | grep -v grep | awk '{print $1}' | xargs -r kill -9 2>/dev/null
	sleep 1
	./forensic2.sh >>"$LOG" 2>&1 || continue
	up=0
	i=0
	while [ $i -lt 40 ]; do
		if ssh $SSH -o ConnectTimeout=5 root@127.0.0.1 'true' >/dev/null 2>&1; then up=1; break; fi
		sleep 3; i=$((i+3))
	done
	[ "$up" = 1 ] || { echo "boot failed" | tee -a "$LOG"; continue; }

	cat ../findings/poc/DF-3017/df3017x.c | ssh $SSH root@127.0.0.1 'cat > /tmp/df3017x.c' >/dev/null 2>&1
	ssh $SSH root@127.0.0.1 '/bin/sh -c "cd /tmp && cc -O2 -pthread -o dx df3017x.c && chmod 755 dx && chown maxx dx && echo BUILD_OK"' >>"$LOG" 2>&1 || continue

	timeout 400 ssh $SSH maxx@127.0.0.1 '/tmp/dx 360' >>"$LOG" 2>&1
	rc=$?
	marker=$(timeout 15 ssh $SSH -o ConnectTimeout=6 root@127.0.0.1 '/bin/sh -c "cat /tmp/df3017.root 2>/dev/null"' 2>/dev/null)
	if [ -n "$marker" ]; then
		echo "=== 2CPU UID0 WIN on attempt $attempt ===" | tee -a "$LOG"
		timeout 20 ssh $SSH root@127.0.0.1 '/bin/sh -c "cat /tmp/df3017.root; ls -la /tmp/df3017*; cat /tmp/df3017.pwned 2>/dev/null"' >>"$LOG" 2>&1
		exit 0
	fi
	if grep -q "panic:" /tmp/opencode/boot2cpu.log 2>/dev/null; then
		grep -m1 -A6 "panic:" /tmp/opencode/boot2cpu.log >>"$LOG" 2>/dev/null
	fi
	echo "--- rc=$rc marker=none ---" | tee -a "$LOG"
done
echo "=== no 2cpu win after $attempt attempts ===" | tee -a "$LOG"
exit 2
