#!/bin/sh
set -eu
[ -r conf ] && . ./conf
# gitqueue@<path>@<branch>[@<user>:<group>[@<queuename>]]
# e.g. gitqueue@__usr__src@master@pkgbuild:pkgbuild@shared_queue
# The repository must be read/writable by the user
myifs="${IFS}"
IFS="@"
i=0
for f in ${PWD}; do
	case ${i} in
	0) ;;
	1) REPO_PATH=$(echo "${f}" | sed 's,__,/,g') ;;
	2) BRANCH="${f}" ;;
	3) GITUSER="${f}" ;;
	4) QUEUE="${f}" ;;
	5) exit 1 ;;
	esac
	i=$((i + 1))
done
IFS="${myifs}"
: "${GIT:="/usr/local/bin/git"}"
: "${GITUSER:="nobody:nobody"}"
: "${LOGGER:="/usr/local/etc/runit/logger"}"
: "${NQ:="/usr/local/bin/nq"}"
: "${QUEUE:="${GITUSER}/${REPO_PATH}"}"
: "${NQDIR:="/var/db/gitqueue/${QUEUE}"}"
: "${SNOOZE_ARGS="-H'*' -M'/5'"}"
export REPO_PATH
export BRANCH
export GIT
export LOGGER
export NQ
export NQDIR
export QUEUE
install -d -m700 -o "${GITUSER%%:*}" -g "${GITUSER##*:}" "${NQDIR}"
chown -R "${GITUSER}" "${NQDIR}"
# shellcheck disable=SC2086
exec chpst -u "${GITUSER}" /usr/local/bin/snooze ${SNOOZE_ARGS} "${PWD}/update" 2>&1
