#!/bin/bash
set -eux
set -o pipefail

sudo apt-get update
sudo DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
     busybox-static \
     python3-venv

if ! command -v tox >/dev/null 2>&1; then
    python3 -m venv venv
    venv/bin/pip install "tox>=4.22"
    # shellcheck source=/dev/null
    . venv/bin/activate
fi

# Fail if lxc command isn't available
if ! command -v lxc; then
    echo "lxc command not available, aborting (hint: snap install lxd)" >&2
    exit 1
fi

# Make sure a client.{crt,key} exist by trying to add a bogus remote
lxc remote add foo 127.0.0.1:1234 2>/dev/null || true

lxc config set core.https_address 127.0.0.1
if lxc info | grep -qwF explicit_trust_token; then
    LXD_TOKEN="$(lxc config trust add --name pylxd --quiet)"
    export LXD_TOKEN
else
    lxc config set core.trust_password password
fi

if ! lxc storage show default >/dev/null 2>&1; then
    lxc storage create default dir
    lxc profile device add default root disk path=/ pool=default
fi

# Save a copy of the server cert for verification by pylxd client using "https://127.0.0.1:8443"
if [ -e /var/snap/lxd/common/lxd/server.crt ]; then
    mkdir -p ~/snap/lxd/common/config/servercerts
    cp /var/snap/lxd/common/lxd/server.crt ~/snap/lxd/common/config/servercerts/127.0.0.1.crt
fi

# LXD 4 has a different `lxc config trust list` output format
LXD_MAJOR_VER="$(lxc version | awk -F. '/Server version:/ {print $1}' | cut -d" " -f 3)"
save_trust_list() {
    if [ "${LXD_MAJOR_VER}" -gt 4 ]; then
        lxc config trust list --format csv | awk -F, '{print $4}' | sort
    else
        lxc config trust list --format csv | awk -F, '{print $1}' | sort
    fi
}

# Save the list of trusted certs
OLD_TRUST_LIST="$(mktemp)"
save_trust_list > "${OLD_TRUST_LIST}"

# Report which LXD version is being tested
snap list lxd || true
lxc version

# finally run the integration tests
tox -e integration

# Remove any cert added to the trusted list by the integration tests
NEW_TRUST_LIST="$(mktemp)"
save_trust_list > "${NEW_TRUST_LIST}"

for cert in $(comm -13 "${OLD_TRUST_LIST}" "${NEW_TRUST_LIST}"); do
    lxc config trust remove "${cert}"
done
rm -f "${OLD_TRUST_LIST}" "${NEW_TRUST_LIST}"

if ! lxc info | grep -qwF explicit_trust_token; then
    lxc config unset core.trust_password || true
fi
lxc config unset core.https_address || true
