# --- Configuration ---
IMG_PATH="/srv/sbuild/qemu/sid-amd64.img"
MOUNT_DIR="/mnt/sbuild_img"
CHROOT_NAME="temp-img-chroot"
CPU_FLAG="Penryn"
PACKAGE=$1

if [ -z "$PACKAGE" ]; then
    echo "Usage: $0 <package_name>"
    exit 1
fi

# 1. Clean up any previous failed mounts
sudo umount -R $MOUNT_DIR 2>/dev/null || true
sudo qemu-nbd --disconnect /dev/nbd0 2>/dev/null || true

# 2. Mount the image
echo "Connecting image..."
sudo modprobe nbd
sudo qemu-nbd --connect=/dev/nbd0 "$IMG_PATH"
sleep 1 # Wait for partitions to register

# Create mount point and mount the first partition (adjust p1 if necessary)
sudo mkdir -p $MOUNT_DIR
sudo mount /dev/nbd0p1 $MOUNT_DIR

# 3. Setup QEMU-User environment
echo "Setting up qemu-user-static..."
# Copy the static binary into the image so the chroot can execute it
sudo cp /usr/bin/qemu-x86_64 "$MOUNT_DIR/usr/bin/qemu-x86_64-static"

# Bind mount system paths
for i in /dev /dev/pts /proc /sys /run; do
    sudo mount -B $i "$MOUNT_DIR$i"
done

# 4. Create temporary schroot config
echo "Configuring schroot..."
SCHROOT_CONF="/etc/schroot/chroot.d/$CHROOT_NAME"
sudo bash -c "cat > $SCHROOT_CONF" <<EOF
[$CHROOT_NAME]
description=Temporary chroot from $IMG_PATH
directory=$MOUNT_DIR
type=directory
users=$(whoami)
groups=sbuild
root-groups=sbuild
profile=sbuild
EOF

# 5. Run the build with the CPU flag
echo "Starting build with QEMU_CPU=$CPU_FLAG..."
# QEMU_CPU is the environment variable used by qemu-user to set the CPU model
export QEMU_CPU="$CPU_FLAG"

# Run sbuild
# --chroot points to the [name] we defined in the .conf file above
sbuild -d testing --chroot "$CHROOT_NAME" "$PACKAGE"

# 6. Cleanup
echo "Cleaning up..."
sudo rm "$SCHROOT_CONF"
sudo umount -R $MOUNT_DIR
sudo qemu-nbd --disconnect /dev/nbd0
sudo rmdir $MOUNT_DIR

echo "Build complete."

