#!/bin/bash
# Build initramfs for CVE-2026-31694 FUSE readdir OOB write test
# Creates a cpio.gz initramfs with busybox, fuse_evil, and fuse.ko
set -e

WORK="${1:-/tmp/initramfs-build}"
CPIO_OUT="${2:-/tmp/initramfs.cpio.gz}"

ROOT="${PRUVA_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
CACHE_DIR="${PRUVA_CACHE:-/data/pruva/project-cache/6cba72b6-b104-4ebf-be7b-01f748e87ccf}"

rm -rf "$WORK"
mkdir -p "$WORK"/{bin,dev,proc,sys,mnt/fuse,tmp,usr/bin,usr/sbin,lib/modules}

# Copy busybox
cp /usr/bin/busybox "$WORK/bin/busybox"
chmod +x "$WORK/bin/busybox"

# Create busybox symlinks
for cmd in sh mount umount mkdir dmesg insmod modprobe cat grep uname \
           poweroff halt reboot ls echo sleep kill ps ln mknod chmod \
           sysctl date head tail wc cp mv rm find vi; do
    ln -sf busybox "$WORK/bin/$cmd"
done

# Copy fuse_evil
cp "$ROOT/repro/fuse_evil" "$WORK/fuse_evil"
chmod +x "$WORK/fuse_evil"

# Copy fuse.ko if it exists (for KASAN kernel approach)
FUSE_KO=$(find "$CACHE_DIR/linux-build-vuln" -name "fuse.ko" -type f 2>/dev/null | head -1)
if [ -n "$FUSE_KO" ] && [ -f "$FUSE_KO" ]; then
    cp "$FUSE_KO" "$WORK/fuse.ko"
    echo "Included fuse.ko from $FUSE_KO"
else
    echo "Warning: fuse.ko not found (will rely on built-in FUSE)"
fi

# Create init script
cat > "$WORK/init" <<'INITEOF'
#!/bin/busybox sh
export PATH=/bin:/usr/bin:/sbin:/usr/sbin
# Mount basic filesystems
/bin/busybox mount -t proc proc /proc 2>/dev/null
/bin/busybox mount -t sysfs sysfs /sys 2>/dev/null
/bin/busybox mount -t devtmpfs devtmpfs /dev 2>/dev/null

# Try to load fuse module if not built-in
if ! grep -q fuse /proc/filesystems 2>/dev/null; then
    /bin/busybox insmod /fuse.ko 2>/dev/null || true
fi

# Run the FUSE exploit
/fuse_evil

# Power off
/bin/busybox poweroff -f
INITEOF
chmod +x "$WORK/init"

# Build cpio archive
cd "$WORK"
find . | cpio -o -H newc 2>/dev/null | gzip > "$CPIO_OUT"
echo "Initramfs built: $CPIO_OUT ($(du -h "$CPIO_OUT" | cut -f1))"
