#!/bin/sh

source /etc/conf.d/eworm-repo
source /usr/lib/eworm/nice

function help() {
	echo "usage: ${0} [OPTIONS]"
	echo
	echo "where OPTIONS are:"
	echo " -d  delete non-root snapshots"
	echo " -h  show this help"
	echo " -u  update snapshots"
	echo " -U  update all (including non-root) snapshots"
}

UPDATE=0
UPDATEALL=0
DELETE=0

while getopts "dhuU" opt; do
	case ${opt} in
		d)
			DELETE=1
			;;
		h)
			help
			exit 0
			;;
		u)
			UPDATE=1
			;;
		U)
			UPDATE=1
			UPDATEALL=1
			;;
	esac
done

if [ "${UPDATE}" -eq 0 ] && [ "${DELETE}" -eq 0 ]; then
	echo "No update, no delete... Nothing to do?" >&2
	exit 1
fi

for CHROOT in $(cd /var/lib/archbuild/ && find -mindepth 2 -maxdepth 2 -type d | sort); do
	CHROOT="${CHROOT#./}"
	figlet -f small -w "$(stty size | cut -d' ' -f2)" "${CHROOT}:"

	exec 8> /var/lib/archbuild/${CHROOT}.lock

	if flock --exclusive --nonblock 8; then
		echo "Locked '${CHROOT}'."

		if [ "${UPDATEALL}" -eq 1 ] || { [ "${UPDATE}" -eq 1 ] && [ "$(basename ${CHROOT})" = "root" ]; }; then
			echo "Updating '${CHROOT}'..."
			arch-nspawn /var/lib/archbuild/${CHROOT} --bind=/var/cache/pacman/pkg/ pacman -Syu --noconfirm
		elif [ "${DELETE}" -eq 1 ] && [ "$(basename ${CHROOT})" != "root" ]; then
			if [ "$(stat --file-system --format=%T /var/lib/archbuild/${CHROOT})" = 'btrfs' ]; then
				for RECURSIVE in $(btrfs subvolume list --sort=-path -o /var/lib/archbuild/${CHROOT} | cut -d' ' -f9); do
					echo "Deleting '${RECURSIVE}'..."
					btrfs subvolume delete -c /var/lib/archbuild/${RECURSIVE}
				done
				echo "Deleting '${CHROOT}'..."
				btrfs subvolume delete -c /var/lib/archbuild/${CHROOT}
			else
				echo "Deleting '${CHROOT}'..."
				rm -r /var/lib/archbuild/${CHROOT}
			fi
		else
			echo "Ignoring '${CHROOT}'..."
		fi

		echo "Unlocking '${CHROOT}'..."
		flock --unlock 8
	else
		echo "Subvolume '${CHROOT}' is locked, skipping." >&2
	fi
done
