#!/bin/bash
set -euo pipefail

# Simple Debian installation script for qcow2
# This creates a basic Debian system that can later be converted to bootc

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

echo "Creating Debian installation in qcow2 image..."

# Create rootfs directory
mkdir -p "$ROOTFS_DIR"

# Mount the qcow2 image
sudo losetup -fP "$QCOW2_IMAGE"
LOOP_DEVICE=$(sudo losetup -j "$QCOW2_IMAGE" | cut -d: -f1)

# Create partition table
sudo parted "$LOOP_DEVICE" mklabel gpt
sudo parted "$LOOP_DEVICE" mkpart primary ext4 1MiB 100%

# Format the partition
sudo mkfs.ext4 "${LOOP_DEVICE}p1"

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

# Install Debian base system
echo "Installing Debian base system..."
sudo debootstrap --arch=amd64 trixie "$ROOTFS_DIR" http://deb.debian.org/debian

# 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 \
    systemd \
    openssh-server \
    curl \
    wget \
    vim \
    nano

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

# Set root password
sudo chroot "$ROOTFS_DIR" passwd root

# Enable SSH
sudo chroot "$ROOTFS_DIR" systemctl enable ssh

# Install GRUB
sudo chroot "$ROOTFS_DIR" grub-install --target=x86_64-efi --efi-directory=/boot/efi
sudo chroot "$ROOTFS_DIR" update-grub

# Cleanup
sudo umount "$ROOTFS_DIR"
sudo losetup -d "$LOOP_DEVICE"

echo "Debian installation completed!"
echo "Image: $QCOW2_IMAGE"
echo "You can now boot this image and install bootc manually"








