#!/bin/sh
set -eu

# Default to loop storage pool if /dev/nvme0n1p3 doesn't exist.
storageDevice=""
if [ -f "/dev/nvme0n1p3" ]; then
  storageDevice="/dev/nvme0n1p3"
fi

cleanup() {
    echo ""
    if [ "${FAIL}" = "1" ]; then
        echo "Test failed"
        exit 1
    fi

    echo "Test passed"
    exit 0
}

FAIL=1
trap cleanup EXIT HUP INT TERM

# Install test dependencies
apt-get remove --purge cloud-init --yes
apt-get install --yes curl zfsutils-linux

# Install Incus
curl -sL https://pkgs.zabbly.com/get/incus-daily | sh

# Configure Incus
incus storage create default zfs source="${storageDevice}"
incus profile device add default root disk path=/ pool=default
incus network create incusbr0
incus profile device add default eth0 nic network=incusbr0 name=eth0

# Launch a test container
echo "==> Launching a test container"
incus launch images:ubuntu/20.04/cloud c1
sleep 10

echo "==> Installing yubikey tools"
incus exec c1 -- apt-get install --no-install-recommends --yes yubikey-manager

echo "==> Validating as non-working"
! incus exec c1 -- ykman info || false

echo "==> Passing all USB devices and validating"
incus config device add c1 usb usb
incus exec c1 ykman info

echo "==> Removing all devices"
incus config device remove c1 usb
! incus exec c1 ykman info || false

echo "==> Passing the specific vendor"
incus config device add c1 usb usb vendorid=1050
incus exec c1 ykman info
incus config device remove c1 usb

echo "==> Passing the specific vendor and product"
incus config device add c1 usb usb vendorid=1050 productid=0010
incus exec c1 ykman info
incus config device remove c1 usb

echo "==> Passing the wrong vendor"
incus config device add c1 usb usb vendorid=1051
! incus exec c1 ykman info || false
incus config device remove c1 usb

echo "==> Passing the wrong product"
incus config device add c1 usb usb vendorid=1050 productid=0011
! incus exec c1 ykman info || false
incus config device remove c1 usb

echo "==> Validating working scenario with specific device after reboot"
incus config device add c1 usb usb vendorid=1050 productid=0010
incus exec c1 ykman info
incus restart c1
incus exec c1 ykman info
incus config device remove c1 usb

FAIL=0
