#!/bin/sh

set -e
set -x

# Find primary interface (default route with lowest metric)
IFACE="$(ip -o -4 route show to default | sort -k11 -n | head -n 1 | awk '{print $5}')"

# Verify libvirt IPs are not currently assigned
if $(ip addr | grep -q "192.168.122.1"); then
    echo "ERROR: IP 192.168.122.1 shouldn't be there."
    exit 1;
fi
if $(ip addr | grep -q "192.168.123.1"); then
    echo "ERROR: IP 192.168.123.1 shouldn't be there."
    exit 1;
fi

# Consume primary libvirt IP, to trigger fallback condition
ip addr add 192.168.122.1 dev $IFACE

# Set up virbr0 through maintainer scripts
apt -y install libvirt-daemon-config-network | grep -B2 -A2 "Changing to free 192.168.123.1/24"
cat /etc/libvirt/qemu/networks/default.xml
virsh net-list

# Confirm IP addresses are correctly assigned
ip addr show $IFACE | grep -q "192.168.122.1"
ip addr show virbr0 | grep -q "192.168.123.1"

echo 'Network test successful'
exit 0
