#!/bin/bash
set -euo pipefail

# Simple script to build a bootable Debian qcow2 image
# This creates a working Debian system that can be used as a base for bootc

QCOW2_IMAGE="./output/debian-bootc.qcow2"
ROOTFS_DIR="./output/rootfs"
SIZE="10G"

echo "Building bootable Debian qcow2 image..."

# Clean up any existing work
sudo umount "$ROOTFS_DIR" 2>/dev/null || true
sudo losetup -d /dev/loop0 2>/dev/null || true
rm -rf "$ROOTFS_DIR"

# Create rootfs directory
mkdir -p "$ROOTFS_DIR"

# Create qcow2 image if it doesn't exist
if [[ ! -f "$QCOW2_IMAGE" ]]; then
    echo "Creating qcow2 image ($SIZE)..."
    qemu-img create -f qcow2 "$QCOW2_IMAGE" "$SIZE"
fi

# Set up loop device
echo "Setting up loop device..."
sudo losetup -fP "$QCOW2_IMAGE"
LOOP_DEVICE=$(sudo losetup -j "$QCOW2_IMAGE" | cut -d: -f1)
echo "Using loop device: $LOOP_DEVICE"

# Wait a moment for the loop device to be ready
sleep 2

# Create partition table and partition
echo "Creating partition table..."
sudo parted "$LOOP_DEVICE" mklabel gpt
sudo parted "$LOOP_DEVICE" mkpart primary ext4 1MiB 100%
sudo parted "$LOOP_DEVICE" set 1 esp on

# Refresh partition table
sudo partprobe "$LOOP_DEVICE"
sleep 1

# Format the partition
echo "Formatting partition..."
sudo mkfs.ext4 -F "${LOOP_DEVICE}p1"

# Mount the partition
echo "Mounting partition..."
sudo mount "${LOOP_DEVICE}p1" "$ROOTFS_DIR"

# Install Debian base system
echo "Installing Debian base system (this may take a while)..."
sudo debootstrap --arch=amd64 trixie "$ROOTFS_DIR" http://deb.debian.org/debian

# Configure apt sources
echo "Configuring apt sources..."
sudo tee "$ROOTFS_DIR/etc/apt/sources.list" > /dev/null << 'EOF'
deb http://deb.debian.org/debian trixie main
deb http://deb.debian.org/debian trixie-updates main
deb http://security.debian.org/debian-security trixie-security main
EOF

# Install essential packages
echo "Installing essential packages..."
sudo chroot "$ROOTFS_DIR" apt-get update
sudo chroot "$ROOTFS_DIR" apt-get install -y \
    linux-image-amd64 \
    grub-efi-amd64 \
    grub-pc-bin \
    systemd \
    openssh-server \
    curl \
    wget \
    vim \
    nano \
    sudo \
    network-manager \
    cloud-init \
    qemu-guest-agent

# Configure the system
echo "Configuring system..."

# Set root password
echo "Setting root password..."
echo "root:debian" | sudo chroot "$ROOTFS_DIR" chpasswd

# Create a user
echo "Creating user 'debian'..."
sudo chroot "$ROOTFS_DIR" useradd -m -s /bin/bash debian
echo "debian:debian" | sudo chroot "$ROOTFS_DIR" chpasswd
sudo chroot "$ROOTFS_DIR" usermod -aG sudo debian

# Enable services
echo "Enabling services..."
sudo chroot "$ROOTFS_DIR" systemctl enable ssh
sudo chroot "$ROOTFS_DIR" systemctl enable NetworkManager
sudo chroot "$ROOTFS_DIR" systemctl enable qemu-guest-agent

# Configure network
echo "Configuring network..."
sudo tee "$ROOTFS_DIR/etc/netplan/01-netcfg.yaml" > /dev/null << 'EOF'
network:
  version: 2
  renderer: NetworkManager
  ethernets:
    eth0:
      dhcp4: true
EOF

# Configure SSH
echo "Configuring SSH..."
sudo tee "$ROOTFS_DIR/etc/ssh/sshd_config.d/99-custom.conf" > /dev/null << 'EOF'
PasswordAuthentication yes
PermitRootLogin yes
EOF

# Install GRUB
echo "Installing GRUB..."
sudo chroot "$ROOTFS_DIR" grub-install --target=x86_64-efi --efi-directory=/boot/efi --bootloader-id=debian
sudo chroot "$ROOTFS_DIR" grub-install --target=i386-pc "$LOOP_DEVICE"
sudo chroot "$ROOTFS_DIR" update-grub

# Create fstab
echo "Creating fstab..."
ROOT_UUID=$(sudo blkid -s UUID -o value "${LOOP_DEVICE}p1")
sudo tee "$ROOTFS_DIR/etc/fstab" > /dev/null << EOF
# /etc/fstab: static file system information.
UUID=$ROOT_UUID / ext4 defaults 0 1
EOF

# Set hostname
echo "Setting hostname..."
echo "debian-bootc" | sudo tee "$ROOTFS_DIR/etc/hostname" > /dev/null

# Configure timezone
echo "Configuring timezone..."
sudo chroot "$ROOTFS_DIR" timedatectl set-timezone UTC

# Clean up
echo "Cleaning up..."
sudo chroot "$ROOTFS_DIR" apt-get clean
sudo chroot "$ROOTFS_DIR" apt-get autoremove -y

# Unmount and cleanup
echo "Unmounting and cleaning up..."
sudo umount "$ROOTFS_DIR"
sudo losetup -d "$LOOP_DEVICE"

echo ""
echo "✅ Debian qcow2 image created successfully!"
echo "📁 Image: $QCOW2_IMAGE"
echo "🔑 Login: root/debian or debian/debian"
echo "🌐 SSH: ssh root@<vm-ip> or ssh debian@<vm-ip>"
echo ""
echo "To boot the image:"
echo "qemu-system-x86_64 -m 2G -drive file=$QCOW2_IMAGE,format=qcow2 -netdev user,id=net0 -device e1000,netdev=net0"
