#!/bin/sh -eu
CNAME="lxc-android-$(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}"

# Copy the cross-file script
incus file push /lxc-ci/deps/cross-file.txt "${CNAME}/build/"

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

# Copy libcap
mkdir -p /build/android/data/lxc/lxc/lib/
cp -P /build/libcap/libcap/libcap.so* /build/android/data/lxc/lxc/lib/

if [ -e autogen.sh ]; then
    # Environment
    export PATH=/build/ndk/toolchains/arm-linux-androideabi-4.9/prebuilt/linux-x86_64/bin/:${PATH}
    export CC="arm-linux-androideabi-gcc --sysroot=/build/ndk/platforms/android-21/arch-arm/"
    export DESTDIR=/build/android
    export BUILD_CC=gcc
    export LD=arm-linux-androideabi-ld

    # Build LXC
    cd /build/source/
    ./autogen.sh
    ./configure --host=arm-eabi CFLAGS=-I/build/libcap/libcap/include/ \
        --disable-api-docs --disable-lua --disable-python --enable-tests \
        --disable-examples --prefix=/data/lxc/lxc --host=arm-linux-androideabi \
        --with-runtime-path=/cache/ --with-config-path=/data/lxc/containers/
    make
    make install
else
    meson setup build/ --cross-file /build/cross-file.txt \
        -Dprefix=/data/lxc/lxc -Dinit-script=[] -Dman=false \
        -Dpam-cgroup=false -Dtests=true \
        -Dglobal-config-path=/data/lxc/containers/ \
        -Druntime-path=/cache/
    ninja -C build
    ninja -C build install
fi

# Generate tarball
tar -zcf /build/lxc-android.tar.gz -C /build/android data
exit 0
EOF
) | incus file push - "${CNAME}/root/build.sh" --mode=755
incus exec "${CNAME}" -- /root/build.sh "$@"

incus file pull "${CNAME}/build/lxc-android.tar.gz" "${TARGET}"

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