#!/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

# Acquire the lock from a short lived client: the client is gone as
# soon as acquire returns. The holder must notice that its client is
# gone, and free the lock by itself, so that an aborted build never
# leaves the lock held forever.
( "${SCRIPT}" acquire && touch "${WORK}/acquired" ) &
CLIENT=$!

i=0
while ! [ -f "${WORK}/acquired" ] ; do
	i=$(( ${i} + 1 ))
	if [ "${i}" -gt 100 ] ; then
		echo "${ME}: acquire never returned"
		kill "${CLIENT}" 2>/dev/null || true
		exit 1
	fi
	sleep 0.1
done

read HOLDER CLIENT_PID < "${WORK}/pid"
if [ "${CLIENT_PID}" != "${CLIENT}" ] ; then
	echo "${ME}: the holder's client must be ${CLIENT}, got ${CLIENT_PID}"
	exit 1
fi

# The holder must exit by itself shortly after its client is gone.
i=0
while kill -0 "${HOLDER}" 2>/dev/null ; do
	i=$(( ${i} + 1 ))
	if [ "${i}" -gt 100 ] ; then
		echo "${ME}: the holder must exit when its client is gone"
		kill "${HOLDER}" 2>/dev/null || true
		exit 1
	fi
	sleep 0.1
done

exit 0
