#!/bin/bash
# Build PyQt6 without SSSE4.2 and POPCNT requirements using QEMU with restricted CPU

echo "🚀 Building PyQt6 with restricted CPU using QEMU"
echo "================================================"

# Check and install required tools
echo "🔧 Checking for required tools..."
if ! command -v sbuild-qemu-create &> /dev/null || ! command -v sbuild &> /dev/null; then
    echo "   📦 Installing sbuild and qemu..."
    sudo apt-get update
    sudo apt-get install -y sbuild sbuild-qemu qemu-system-x86 qemu-user qemu-user-binfmt qemu devuan-archive-keyring
else
    echo "   ✅ Required tools are available"
fi

# Create symlink for qemu command
#if [ -f /usr/bin/qemu-system-x86_64 ]; then
#    sudo ln -sf /usr/bin/qemu-system-x86_64 /usr/bin/qemu
#el
if [ -f /usr/bin/qemu-amd64 ]; then
    sudo ln -sf /usr/bin/qemu-amd64 /usr/bin/qemu
elif [ -f /usr/bin/qemu-x86_64 ]; then
    sudo ln -sf /usr/bin/qemu-x86_64 /usr/bin/qemu
else
    echo "   ⚠️  No suitable QEMU binary found"
fi

IMG="/srv/sbuild/qemu/sid-amd64.img"
PACKAGE="python3-pyqt6"

# 1. Create QEMU image if it doesn't exist
if [ ! -f "$IMG" ]; then
    echo "📦 Creating QEMU image..."
    sudo mkdir -p /srv/sbuild/qemu/
    sudo sbuild-qemu-create -o "$IMG" daedalus http://deb.devuan.org/
else
    echo "📦 QEMU image already exists"
fi

# Update the QEMU image
echo "🔄 Updating QEMU image..."
sudo sbuild-qemu-update "$IMG"


# --- Configuration ---
IMG_PATH=$IMG
MOUNT_DIR="/mnt/sbuild_img"
CHROOT_NAME="temp-img-chroot"
CPU_FLAG="Penryn"
PACKAGE_build="pyqt6"

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"

read  aaa

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

# 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."

# Extract the built package to pyqt6_built directory
if ls ${PACKAGE}_*.deb 1> /dev/null 2>&1; then
    echo "📦 Extracting built package to pyqt6_built/..."
    mkdir -p pyqt6_built
    dpkg -x ${PACKAGE}_*.deb pyqt6_built/
    echo "✅ PyQt6 extracted to pyqt6_built/"
else
    echo "❌ No .deb file found after build"
fi

echo "✅ PyQt6 build completed!"

