#!/bin/sh -eux
CNAME="docker-$(uuidgen)"

cleanup() {
    incus delete --force "${CNAME}"
}

trap cleanup EXIT HUP INT TERM

# Create the container
incus launch images:debian/12 "${CNAME}" -c security.nesting=true "$@"

(
cat << EOF
#!/bin/sh
# Wait for network
while :; do
    ping -W1 -c1 linuxcontainers.org >/dev/null 2>&1 && break
    sleep 1
done

set -eux

# Install distro docker
apt-get update --yes --force-yes
apt-get install --no-install-recommends --yes --force-yes apparmor docker.io wget

# Workaround for AppArmor bug (https://gitlab.com/apparmor/apparmor/-/merge_requests/1112)
sed -i "s/lxd-/incus-/g" /lib/apparmor/rc.apparmor.functions
systemctl start apparmor

# Stop the distro docker
systemctl stop docker.service
systemctl stop docker.socket

# Download binaries built from current git head of the Docker repo.
for BIN in docker dockerd docker-containerd docker-containerd-shim docker-init docker-proxy docker-runc; do
    wget -q "https://master.dockerproject.org/linux/\$(uname -m)/\${BIN}" -O "/usr/bin/\${BIN}" && \
        chmod +x "/usr/bin/\${BIN}"
done

# Start docker again
systemctl start docker
sleep 5

# Test whether we can pull a simple Docker image.
docker pull busybox:latest

# Test whether we can remove a simple Docker image.
docker rmi busybox:latest

# Show docker info (client and daemon version, etc.)
docker info

# Run a basic hello-world
docker run hello-world
EOF
) | incus exec "${CNAME}" -- sh -eux
