#!/bin/sh
# Cloud-Init User Data script
# This script is executed by cloud-init on first boot.

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

echo "Starting Provisioning..."

# --- Network Reliability Fixes ---
echo "Applying network fixes..."
sysrc background_dhclient="YES"
sysrc defaultrouter_delay="10"

echo "Restarting network..."
service netif restart
service routing restart
if ! ifconfig vtnet0 | grep -q "inet "; then
    dhclient vtnet0
fi

# Route fix for QEMU user networking if DHCP failed to add default GW
if ! netstat -rn | grep -q "^default"; then
    echo "Default route missing, adding 10.0.2.2..."
    route add default 10.0.2.2
fi

# Force Google DNS if empty or likely broken
echo "nameserver 8.8.8.8" >> /etc/resolv.conf

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

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

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

# list block devices and try to find the CDROM
ls -al /dev/vtbd* /dev/cd* 2>/dev/null || true

# Try typical CDROM devices
# On QEMU with virtio-scsi or ide, it might be cd0 or cd1.
# With virtio-blk, it might be vtbd* (but CDROM is usually cd*)
for dev in /dev/cd0 /dev/cd1 /dev/vtbd1; do
    if [ -c "$dev" ]; then
        echo "Trying to mount $dev..."
        # Try mounting
        if mount_cd9660 "$dev" /mnt/payload >/dev/null 2>&1; 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"
         sh "$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
         shutdown -p now
    else
         echo "Error: provision.sh not found at $SCRIPT"
         echo "CI_TEST_FAILED"
         shutdown -p now
    fi
else
    echo "Error: Could not mount CI payload ISO"
    echo "CI_TEST_FAILED"
    shutdown -p now
fi