#!/bin/sh
# Licensed under the GPL: https://www.gnu.org/licenses/gpl-3.0.en.html
# For details: reprotest/debian/copyright
set -eu

# generate temporary container name
generate_container_name() {
    while true; do
        CONTAINER=$(mktemp adt-prepare-XXX -u)
        lxc info "$CONTAINER" >/dev/null 2>&1 || break
    done
}

# detect apt proxy
proxy_detect() {
    if [ -z "${ADT_APT_PROXY:-}" ]; then
        RES=`apt-config shell proxy Acquire::http::Proxy`
        eval $RES
        if echo "${proxy:-}" | egrep -q '(localhost|127\.0\.0\.[0-9]*)'; then
            # translate proxy address to one that can be accessed from the
            # running container
            local bridge_ip=$(sh -c '. /etc/default/lxd-bridge; echo $LXD_IPV4_ADDR' 2>/dev/null)
            if [ -n "$bridge_ip" ]; then
                ADT_APT_PROXY=$(echo "$proxy" | sed -r "s#localhost|127\.0\.0\.[0-9]*#$bridge_ip#")
            fi
            if [ -n "${ADT_APT_PROXY:-}" ]; then
                echo "Detected local apt proxy, using $ADT_APT_PROXY as container proxy"
            fi
        elif [ -n "${proxy:-}" ]; then
            echo "Using $ADT_APT_PROXY as container proxy"
            ADT_APT_PROXY="$proxy"
        fi
    fi
}

setup() {
    # set up apt proxy for the container
    if [ -n "${ADT_APT_PROXY:-}" ] && [ "$ADT_APT_PROXY" != "none" ]; then
        echo "Acquire::http::Proxy \"$ADT_APT_PROXY\";" | lxc file push - "$CONTAINER/etc/apt/apt.conf.d/01proxy"
        # work around LP#1548878
        lxc exec "$CONTAINER" -- chmod 644 /etc/apt/apt.conf.d/01proxy
    fi

    # wait until it is booted: lxc exec works and we get a numeric runlevel
    timeout=60
    while [ $timeout -ge 0 ]; do
        timeout=$((timeout - 1))
        sleep 1
        O=`lxc exec "$CONTAINER" runlevel 2>/dev/null </dev/null` || continue
        [ "$O" = "${O%[0-9]}" ] || break
    done
    [ $timeout -ge 0 ] || {
        echo "Timed out waiting for container to boot" >&2
        exit 1
    }

    ARCH=$(lxc exec "$CONTAINER" -- dpkg --print-architecture </dev/null)
    DISTRO=$(lxc exec "$CONTAINER" -- sh -ec 'lsb_release -si 2>/dev/null || . /etc/os-release; echo "${NAME% *}"' </dev/null)
    RELEASE=$(lxc exec "$CONTAINER" -- sh -ec 'lsb_release -sc 2>/dev/null || awk "/^deb/ {sub(/\\[.*\\]/, \"\", \$0); print \$3; quit}" /etc/apt/sources.list' </dev/null)
    echo "Container finished booting. Distribution $DISTRO, release $RELEASE, architecture $ARCH"

    # find setup-testbed script
    for script in $(dirname $(dirname "$0"))/setup-commands/setup-testbed \
                  /usr/share/autopkgtest/setup-commands/setup-testbed; do
        if [ -r "$script" ]; then
            echo "Running setup script $script..."
            lxc exec "$CONTAINER" -- sh < "$script"
            break
        fi
    done
    lxc stop "$CONTAINER"
}

#
# main
#

if [ -z "${1:-}" ]; then
    echo "Usage: $0 <image>" >&2
    exit 1
fi
IMAGE="$1"
CONTAINER=''
trap '[ -z "$CONTAINER" ] || lxc delete -f "$CONTAINER"' EXIT INT QUIT PIPE

proxy_detect
generate_container_name
lxc launch "$IMAGE" "$CONTAINER"
setup

# if there already is a published image, get its fingerprint to clean it up
# afterwards
DISTROLC=$(echo "$DISTRO" | tr '[:upper:]' '[:lower:]')
ALIAS="adt/$DISTROLC/$RELEASE/$ARCH"
DESCRIPTION="autopkgtest $DISTRO $RELEASE $ARCH"

lxc publish "$CONTAINER" --alias "$ALIAS" --public description="$DESCRIPTION" distribution="$DISTROLC" release="$RELEASE" architecture="$ARCH"

# clean up old images
for i in $(lxc image list | grep "$DESCRIPTION" | grep -v "$ALIAS" | cut -d'|' -f3); do
    echo "Removing previous image $i"
    lxc image delete "$i"
done
