#!/bin/sh
# Run one repository build operation under the common publication lock.
set -eu
cd "$(dirname "$0")/.."

if [ "$#" -eq 0 ]; then
    echo "usage: scripts/with-build-lock COMMAND [ARGUMENT...]" >&2
    exit 2
fi

lock_timeout=${CCLSH_BUILD_LOCK_TIMEOUT:-30}
lock_file=.cclsh-build.lock
if [ -e "$lock_file" ] || [ -L "$lock_file" ]; then
    if [ ! -f "$lock_file" ] || [ -L "$lock_file" ]; then
        echo "cclsh build: build lock is not a regular file" >&2
        exit 1
    fi
else
    (umask 077; : >"$lock_file")
fi
chmod 600 "$lock_file"
exec 9<>"$lock_file"
if ! flock -w "$lock_timeout" 9; then
    echo "cclsh build: timed out waiting for another build" >&2
    exit 1
fi

CCLSH_BUILD_LOCK_PATH=$(realpath -m "$lock_file")
export CCLSH_BUILD_LOCK_PATH
exec "$@"
