#!/bin/sh -eu
CNAME="lxc-tarballs-$(uuidgen)"

# Check arguments
if [ "${1:-}" = "" ] || [ "${2:-}" = "" ] || [ "${3:-}" = "" ] || [ "${4:-}" = "" ] || [ "${5:-}" = "" ]; then
    echo "Usage: ${0} <arch> <repository> <branch> <commit> <target>"
    exit 1
fi

ARCH=${1}
shift
REPO=${1}
shift
BRANCH=${1}
shift
COMMIT=${1}
shift
TARGET=${1}
shift

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

trap cleanup EXIT HUP INT TERM

# Create the container
incus copy "cache-lxc-${ARCH}" "${CNAME}"

# Start the container
incus start "${CNAME}"

set -x

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

set -eux

# Create build directories
mkdir -p /build/android /build/source

# Get the source
git clone "${REPO}" -b "${BRANCH}" /build/source
cd /build/source
git fetch "${REPO}" "+refs/pull/*:refs/remotes/origin/pr/*"
git checkout "${COMMIT}"

# Build the dist tarball
cd /build/source/
if [ -e autogen.sh ]; then
    ./autogen.sh
    ./configure --enable-doc --enable-apidoc --enable-python \
        --prefix=/usr/ --sysconfdir=/etc/ --localstatedir=/var/
fi

make dist
mv *.tar.gz /build/lxc.tar.gz

# Build API doc
if [ -e autogen.sh ]; then
    make -C doc
else
    make
    ( cd doc/api/ && doxygen Doxyfile )
fi

tar -zcf /build/apidoc.tar.gz -C /build/source/doc/api/html/ .

# Build manpages
if [ -e autogen.sh ]; then
    cd /build/source/doc/
else
    cd /build/source/build/doc/
fi

find . | grep \\\\.[0-9]$ | while read line; do
    dst_file="/build/man/\${line}"
    mkdir -p \$(dirname \$dst_file)
    cp \$line \$dst_file
done
tar -zcf /build/manpages.tar.gz -C /build/man/ .

exit 0
EOF
) | incus file push - "${CNAME}/root/build.sh" --mode=755
incus exec "${CNAME}" -- /root/build.sh "$@"

incus file pull "${CNAME}/build/lxc.tar.gz" "${TARGET}"
incus file pull "${CNAME}/build/apidoc.tar.gz" "${TARGET}"
incus file pull "${CNAME}/build/manpages.tar.gz" "${TARGET}"

[ -n "${SUDO_UID:-}" ] && chown "${SUDO_UID}" -R "${TARGET}"
[ -n "${SUDO_GID:-}" ] && chgrp "${SUDO_GID}" -R "${TARGET}"
