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

# Check arguments
if [ "${1:-}" = "" ] || [ "${2:-}" = "" ] || [ "${3:-}" = "" ] || \
        [ "${4:-}" = "" ] || [ "${5:-}" = "" ] || [ "${6:-}" = "" ] || \
        [ "${7:-}" = "" ] || [ "${8:-}" = "" ] || [ "${9:-}" = "" ] || \
        [ "${10:-}" = "" ] || [ "${11:-}" = "" ]; then
    echo "Usage: ${0} <arch> <repository> <branch> <commit> <pkg_repository> <pkg_branch> <pkg_commit> <dist> <release> <pkg_version> <target>"
    exit 1
fi

ARCH=${1}
shift
REPO=${1}
shift
BRANCH=${1}
shift
COMMIT=${1}
shift
PKG_REPO=${1}
shift
PKG_BRANCH=${1}
shift
PKG_COMMIT=${1}
shift
DIST=${1}
shift
RELEASE=${1}
shift
PKG_VERSION=${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

# 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}"

# Get the package source
git clone "${PKG_REPO}" -b "${PKG_BRANCH}" /build/packaging
cd /build/packaging
git fetch "${PKG_REPO}" "+refs/pull/*:refs/remotes/origin/pr/*"
git checkout "${PKG_COMMIT}"

# Environment
export DEBEMAIL="lxc-devel@lists.linuxcontainers.org"
export DEBFULLNAME="LXC snapshot packages"
version="${PKG_VERSION}~$(date +%Y%m%d-%H%M)"
version_orig="\$(echo \$version | cut -d: -f2)"

# Build the dist tarball
cd /build/source/
if [ -e autogen.sh ]; then
    ./autogen.sh
    ./configure
fi
make dist
mv *.tar.gz /build/lxc_\${version_orig}.orig.tar.gz
rm -Rf /build/source/

mkdir /build/dist
cd /build/dist
tar zxf /build/lxc_\${version_orig}.orig.tar.gz --strip 1
cp -R /build/packaging/debian/ /build/dist/debian/
rm -f debian/changelog

dch --create --package lxc -v \${version}-0${DIST}1~${RELEASE} --distribution ${RELEASE} \
    "Automated snapshot build."

debuild -S -sa -us -uc -d
mkdir /build/pkg
mv /build/lxc_* /build/pkg/
exit 0
EOF
) | incus file push - "${CNAME}/root/build.sh" --mode=755
incus exec "${CNAME}" -- /root/build.sh "$@"

incus exec "${CNAME}" -- tar -cf - -C /build/pkg . | tar -xvf - -C "${TARGET}"

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