#!/usr/bin/env bash
# repro.sh — end-to-end dm_setup_md_queue UAF reproduction inside the Docker image.
#
# From the host, with attachments/ as the build context:
#
#   docker build -t dm-setup-md-queue-uaf -f Dockerfile .
#   mkdir -p artifacts
#   # Fully self-contained (builds kernel + guest image inside the container):
#   docker run --rm --privileged --device=/dev/kvm --network=host \
#     -v "$PWD/artifacts:/artifacts" \
#     -e OUTPUT_DIR=/artifacts \
#     dm-setup-md-queue-uaf
#
#   # Or mount a prebuilt bzImage to skip the kernel build:
#   docker run ... -v /path/to/bzImage:/kernel/bzImage:ro \
#     -e KERNEL_IMAGE=/kernel/bzImage ...
#
# Optional env:
#   KERNEL_IMAGE        path to existing KASAN bzImage (skips build-kernel.sh)
#   KERNEL_VERSION      default 6.6.144 (used by build-kernel.sh)
#   OUTPUT_DIR          artifact dir (default /artifacts)
#   RELEASE             Debian guest release (default bookworm)
#   SKIP_KERNEL_BUILD=1 require KERNEL_IMAGE; do not auto-build
#   SKIP_IMAGE_BUILD=1  reuse $OUTPUT_DIR/$RELEASE.img + .id_rsa if present
#   FORCE_KERNEL_BUILD=1 rebuild even if artifacts/bzImage exists
#   VM_PORT / VM_CPUS / VM_MEMORY_MB / RUN_TIMEOUT_SEC
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$SCRIPT_DIR"

OUTPUT_DIR="${OUTPUT_DIR:-/artifacts}"
RELEASE="${RELEASE:-bookworm}"

mkdir -p "$OUTPUT_DIR"

# --- kernel ---
if [[ -n "${KERNEL_IMAGE:-}" && -f "$KERNEL_IMAGE" ]]; then
	echo "[+] Using KERNEL_IMAGE=$KERNEL_IMAGE"
elif [[ -f "$OUTPUT_DIR/bzImage" && "${FORCE_KERNEL_BUILD:-0}" != "1" ]]; then
	KERNEL_IMAGE="$OUTPUT_DIR/bzImage"
	echo "[+] Reusing cached kernel: $KERNEL_IMAGE"
elif [[ "${SKIP_KERNEL_BUILD:-0}" == "1" ]]; then
	echo "KERNEL_IMAGE not set/found and SKIP_KERNEL_BUILD=1" >&2
	exit 1
else
	echo "[+] Building KASAN kernel via build-kernel.sh → $OUTPUT_DIR"
	OUTPUT_DIR="$OUTPUT_DIR" bash "$SCRIPT_DIR/build-kernel.sh"
	KERNEL_IMAGE="$OUTPUT_DIR/bzImage"
fi

if [[ ! -f "$KERNEL_IMAGE" ]]; then
	echo "kernel image not found: $KERNEL_IMAGE" >&2
	exit 1
fi

# --- guest disk ---
IMG="$OUTPUT_DIR/${RELEASE}.img"
KEY="$OUTPUT_DIR/${RELEASE}.id_rsa"

if [[ "${SKIP_IMAGE_BUILD:-0}" == "1" && -f "$IMG" && -f "$KEY" ]]; then
	echo "[+] Reusing existing guest image: $IMG"
else
	echo "[+] Building guest image ($RELEASE) via create-image-userns.sh → $OUTPUT_DIR"
	(
		cd "$OUTPUT_DIR"
		RELEASE="$RELEASE" OUTPUT="$RELEASE" \
			bash "$SCRIPT_DIR/create-image-userns.sh"
	)
fi

chmod 600 "$KEY"

export KERNEL_IMAGE
export VM_IMAGE="$IMG"
export VM_KEY="$KEY"
export VM_PORT="${VM_PORT:-10057}"
export VM_MEMORY_MB="${VM_MEMORY_MB:-2048}"
export VM_CPUS="${VM_CPUS:-4}"
export RUN_TIMEOUT_SEC="${RUN_TIMEOUT_SEC:-240}"
export OUTPUT_DIR

echo "[+] Kernel : $KERNEL_IMAGE"
echo "[+] Image  : $VM_IMAGE"
echo "[+] SSH key: $VM_KEY"
exec bash "$SCRIPT_DIR/run.sh"
