#!/bin/bash
# Cloud-Init User Data script for Ubuntu
# This script is executed on first boot.

# Redirect output to console for QEMU logging
exec > /dev/console 2>&1

echo "Starting Provisioning..."

# --- Network Sanity ---
echo "Checking network..."

# Wait for network online
systemctl is-active --quiet network-online.target || systemctl start network-online.target

# Ensure DNS is usable
if ! grep -q "nameserver" /etc/resolv.conf; then
    echo "nameserver 8.8.8.8" >> /etc/resolv.conf
fi

# ---------------------------------

# Ensure we have a valid PATH
export PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin

# Install basic dependencies if needed (optional, depending on your image)
# apt-get update && apt-get install -y traceroute whois

# Find and mount the CI ISO
mkdir -p /mnt/payload
MOUNTED=0

# List block devices for debugging
lsblk || true

# Try typical CDROM devices for QEMU (sr0 is standard for IDE/SATA/SCSI CD-ROMs in Linux)
# /dev/vdb might be used if attached as a second virtio disk instead of a CD drive.
CANDIDATES="/dev/sr0 /dev/sr1 /dev/cdrom /dev/vdb"

for dev in $CANDIDATES; do
    if [ -b "$dev" ]; then
        echo "Trying to mount $dev..."
        # Try mounting as iso9660 or auto
        if mount -t iso9660 -o ro "$dev" /mnt/payload 2>/dev/null || mount -o ro "$dev" /mnt/payload 2>/dev/null; then
            echo "Mounted $dev"
            # verify it's the right one
            if [ -d "/mnt/payload/payload" ]; then
                MOUNTED=1
                break
            else
                echo "Mounted $dev but no payload found, unmounting."
                umount /mnt/payload
            fi
        fi
    fi
done

if [ $MOUNTED -eq 1 ]; then
    SCRIPT="/mnt/payload/payload/testharness/provision.sh"
    if [ -f "$SCRIPT" ]; then
         echo "Executing provision script: $SCRIPT"
         # Execute with bash
         /bin/bash "$SCRIPT"
         EXIT_CODE=$?
         echo "Provision script finished with exit code $EXIT_CODE"
         
         if [ $EXIT_CODE -eq 0 ]; then
             echo "CI_TEST_PASSED"
         else
             echo "CI_TEST_FAILED"
         fi

         # Shutdown after test
         sleep 5
         poweroff
    else
         echo "Error: provision.sh not found at $SCRIPT"
         echo "CI_TEST_FAILED"
         poweroff
    fi
else
    echo "Error: Could not mount CI payload ISO"
    echo "CI_TEST_FAILED"
    poweroff
fi