#!/bin/bash
# Emerge wrapper, uses matter lock file support to avoid
# concurrent execution
_exec_locked() {
	snapshot_lock_file="/var/tmp/.emerge.snapshot.lock"
	matter_lock_file="/var/tmp/.matter_resource.lock"

	flock -x -n "${matter_lock_file}" true
	rc=${?}
	if [ "${rc}" != "0" ]; then
		echo >&2
		echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" >&2
		echo "Matter or the Backup Script is running on this chroot" >&2
		echo "Please be patient, it will eventually terminate..." >&2
		echo "Snapshot lock file = ${snapshot_lock_file}" >&2
		echo "Matter lock file = ${matter_lock_file}" >&2
		echo >&2
		echo "this emerge instance will terminate NOW" >&2
		echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" >&2
		echo >&2
		return 1
	else
		# acquire snapshot read lock in non-blocking, shared mode
		(
			flock -s -n 9 || {
				echo "Hello there," >&2;
				echo "a chroot snapshot is in progress..." >%2;
				echo "Try again later." >&2;
				exit 1;
			}
			# eval $(portageq envvar -v FETCHCOMMAND RESUMECOMMAND PORTAGE_RSYNC_OPTS)
			# add bandwidth limit here
			"${@}"
			exit ${?}
		) 9> "${snapshot_lock_file}"
		return "${?}"
	fi
}

emerge() {
	_exec_locked "/usr/bin/emerge" "${@}"
	return ${?}
}

eit() {
	_exec_locked "/usr/bin/eit" "${@}"
	return ${?}
}