#!/bin/sh

set -e

export LIBVIRT_DEFAULT_URI='lxc:///'

XML=debian/tests/smoke-lxc.xml
DOMAIN=sl

cleanup()
{
    if [ -z "$CLEANED_UP" ]; then
        virsh destroy ${DOMAIN} || true
        virsh undefine ${DOMAIN} || true
        CLEANED_UP=1
    fi
}

check_domain()
{
    virsh list | grep -qs "${DOMAIN}[[:space:]]\+running"
    virsh lxc-enter-namespace --noseclabel ${DOMAIN} /bin/ls /bin/ls
}

trap cleanup EXIT

# This is an upstream bug due to combined cgroup v1/v2 handling
# https://bugs.archlinux.org/task/70174
# https://bugzilla.opensuse.org/show_bug.cgi?id=1183247
# https://gitlab.com/libvirt/libvirt/-/issues/182
# https://bugs.launchpad.net/ubuntu/+source/libvirt/+bug/1934966
# Skip this test (until the upstream issue is resolved) in case v1&v2
# cgroup are present in the test environment.
if [ -n "$(findmnt -lnt cgroup)" ] && [ -n "$(findmnt -lnt cgroup2)" ]; then
    echo "Libvirt >=7.1.0 is known to fail LXC handling (issue 182) - skipping".
    exit 77
fi

set -x
virt-host-validate lxc || exit 0
virsh capabilities
virsh capabilities | grep -qs 'emulator>/usr/lib/libvirt/libvirt_lxc'
virsh capabilities | grep -qs 'os_type>exe'
virt-xml-validate ${XML}
virsh define ${XML}
rm -f /var/log/libvirt/lxc/sl.log
virsh start ${DOMAIN}
# Check virtlogd is running
grep -qs "starting up" /var/log/libvirt/lxc/sl.log
check_domain
# Make sure a restart doesn't termiante the domain
/etc/init.d/libvirtd restart
check_domain
virsh destroy ${DOMAIN}
virsh undefine ${DOMAIN}
CLEANED_UP=1
set +x

echo 'Smoke test of lxc:/// succesful'
exit 0
