#!/usr/bin/env bash
# Depends on lxf
shopt -s nullglob

cleanup() { lxf umount "$cnt"; }

buildscript() {
	cat <<- EOF
		#!/usr/bin/env bash
		# The builder user is already created in the rootfs

		export PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
		export LC_ALL=en_US.UTF-8

		# Network
		dhcpcd eth0

		# Upgrade
		pacman -Suy --noconfirm

		# Build dir
		mkdir -m777 /buildroot

		# Build the damn thing
		cd /buildroot
		sudo -u builder git clone "$pkg_url" .
		sudo -u builder makepkg -s --noconfirm -L
	EOF
}

# Config
wrk_dir='/home/lxc'

# Parameters
pkg_url=$1
pkg_dest=$2
cnt="_makepkg.$$"
cnt_dir="$wrk_dir/containers/$cnt"

# Create new container
lxf -r builder -i base new "$cnt" || exit $?

# Unmount the thing in any case
trap 'cleanup' INT TERM EXIT

# Add the build script
buildscript > "$cnt_dir/rootfs/init"
chmod 755 "$cnt_dir/rootfs/init"

# Start the container
lxc-start -n "$cnt" -F /init || exit $?

# Put the artifacts where asked to
[[ "$pkg_dest" ]] && {
	artifacts=( "$cnt_dir/rootfs/buildroot/"*.pkg.* )

	for i in "${artifacts[@]}"; do
		i_name="${i##*/}"

		printf 'Found artifact: %s\n' "$i_name"
		
		if [[ -f "$pkg_dest/$i_name" ]]; then
			echo "$pkg_dest/$i_name already exists, not overwriting."
		else
			cp -vn "$i" "$pkg_dest"
		fi
	done
}
