#!/bin/sh
# DF-2633 fix validation on the patched kernel: fill dedicated hammer2 to
# the wall, then verify errors now SURFACE:
#  - writes/fsync in the wall regime must report an error (ENOSPC) via the
#    new ip->error channel (next write/fsync after a backend failure),
#  - console must be rate-limited (count lines),
#  - healthy-image dd+md5 roundtrip unaffected.
set -e
cd /root/df2633
cc -O2 -o write2633 write2633.c
cc -O2 -o phase2 phase2.c

echo "=== fill to the wall ==="
rm -f /tmp/h33.img
truncate -s 256M /tmp/h33.img
vnconfig -c vn1 /tmp/h33.img
newfs_hammer2 -L DATA /dev/vn1 >/dev/null
mkdir -p /mnt/h33
mount_hammer2 /dev/vn1@DATA /mnt/h33
df /mnt/h33
./write2633 /mnt/h33 /root/df2633/ctrl 6000 || true
echo "=== phase2 (post-wall probing) ==="
./phase2 /mnt/h33 /root/df2633/ctrl || true
echo "=== retry loop: do subsequent writes/fsyncs report the error? ==="
cat > /tmp/retry.c <<'EOF'
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main(void){
	char buf[4096]; int fd, rc, i;
	memset(buf, 0x41, sizeof(buf));
	fd = open("/mnt/h33/fill.bin", O_WRONLY|O_APPEND);
	if (fd < 0) { printf("RETRY_OPEN_FAIL errno=%d (%s)\n", errno, strerror(errno)); return 0; }
	for (i = 0; i < 5; i++) {
		errno = 0;
		rc = write(fd, buf, sizeof(buf));
		printf("RETRY_WRITE[%d] rc=%d errno=%d (%s)\n", i, rc, errno, rc<0?strerror(errno):"ok");
		if (rc > 0) break;
		sleep(1);
	}
	errno = 0;
	rc = fsync(fd);
	printf("RETRY_FSYNC rc=%d errno=%d (%s)\n", rc, errno, rc?strerror(errno):"ok");
	close(fd);
	return 0;
}
EOF
cc -O2 -o /tmp/retry /tmp/retry.c
sleep 3
/tmp/retry
sleep 3
/tmp/retry
echo "=== healthy roundtrip ==="
umount /mnt/h33 2>/dev/null || echo "(umount of full fs may defer; continuing)" 
vnconfig -u vn1 2>/dev/null || true
truncate -s 64M /tmp/h33r.img
vnconfig -c vn1 /tmp/h33r.img
newfs_hammer2 -L DATA /dev/vn1 >/dev/null
mount_hammer2 /dev/vn1@DATA /mnt/h33
dd if=/dev/urandom of=/mnt/h33/rt.bin bs=1m count=8 2>/dev/null
A=$(md5 -q /mnt/h33/rt.bin)
sync
umount /mnt/h33
mount_hammer2 /dev/vn1@DATA /mnt/h33
B=$(md5 -q /mnt/h33/rt.bin)
echo "md5_live=$A md5_remount=$B"
[ "$A" = "$B" ] && echo ROUNDTRIP_MATCH || echo ROUNDTRIP_MISMATCH
umount /mnt/h33
vnconfig -u vn1
echo "VALIDATION2633_COMPLETE"
