#!/bin/sh

set -e

ME=$(basename $0)
SCRIPT=$(readlink -f ../../../build-tools/pkgos-sbuild-lock)
WORK=$(mktemp -d /tmp/pkgos-sbuild-lock.XXXXXX)
trap 'rm -rf "${WORK}"' EXIT
PKGOS_SBUILD_LOCK_FILE=${WORK}/lock
PKGOS_SBUILD_LOCK_PIDFILE=${WORK}/pid
export PKGOS_SBUILD_LOCK_FILE PKGOS_SBUILD_LOCK_PIDFILE

# A PID file left behind by a long gone holder must not prevent
# acquiring the lock: the new holder takes the flock, and overwrites
# the PID file with the current holder and client PIDs.
printf '999999 999998\n' > "${WORK}/pid"
"${SCRIPT}" acquire
read HOLDER CLIENT < "${WORK}/pid"
if ! kill -0 "${HOLDER}" 2>/dev/null ; then
	echo "${ME}: the new holder must be alive"
	exit 1
fi
if [ "${HOLDER}" = "999999" ] ; then
	echo "${ME}: the stale PID file must have been overwritten"
	exit 1
fi
"${SCRIPT}" release

# Releasing with no lock held at all must still succeed.
"${SCRIPT}" release
exit 0
