#!/usr/bin/env bash
# wrapper for 'pacman' to add flock-based locking

if (( UID == 0 )) && [[ ! $PACMAN_LOCK ]] && [[ ! $FAKEROOTKEY ]] && [[ $1 != "-V" ]]; then
	lock=/run/lock/pacman
	exec {fd}>"$lock" &&
	/usr/bin/flock -xn $fd || {
		if [[ $DEBUG ]]; then
			echo "[$$:$(ps -o cmd= $PPID):$*]"
		fi
		echo -n "waiting for other instances to exit..."
		/usr/bin/flock -x $fd && echo "done"
	} >&2
	dblock=/var/lib/pacman/db.lck
	if [[ -e "$dblock" ]]; then
		if pid=$(pgrep -x pacman); then
			echo "another instance is already running"
			ps -f $pid
			exit 1
		fi
		rm -fi "$dblock"
	fi
	export PACMAN_LOCK=$fd
fi

exec /usr/bin/pacman "$@"
