#!/bin/sh
set -eu
[ -r conf ] && . ./conf

export NQDIR

# While runit takes care of logging output from a service, it won't
# see output from nq-ed jobs, so log messages directly.
_err() {
	${LOGGER} -t gitqueue "[${NQJOBID:=-}] $*"
	exit 1
}

_msg() {
	${LOGGER} -t gitqueue "[${NQJOBID:=-}] $*"
}

_nq() {
	${NQ} -c -q "$@"
}

_repo_needs_update() {
	local_commit=$(${GIT} -C "$1" rev-parse "$2")
	remote_commit=$(${GIT} -C "$1" ls-remote origin "$2")
	[ ! "${local_commit}" = "$(echo "${remote_commit}" | awk '{ print $1 }')" ]
}

_update_repo() {
	_status=$(${GIT} -C "$1" status --porcelain)
	if [ -n "${_status}" ]; then
		_msg "$1 is dirty.  Skipping this update."
		echo "${_status}" | while read -r line; do
			_msg "${line}"
		done
		exit 1
	fi

	_msg "Updating $1"
	${GIT} -C "$1" checkout -q "$2"
	${GIT} -C "$1" fetch -q origin
	${GIT} -C "$1" reset -q --hard "origin/$2"
}

# Check again at a later time if a previous build is still running
_nq -t || exit 0

# shellcheck disable=SC2154
if [ -z "${REPO_PATH}" ] || [ -z "${BRANCH}" ]; then
	exit 1
fi
cd "${REPO_PATH}"
if [ -x "${REPO_PATH}/.gitqueue.d/check" ]; then
	"${REPO_PATH}/.gitqueue.d/check" "${QUEUE}" "${REPO_PATH}" "${BRANCH}" || exit 0
else
	_repo_needs_update "${REPO_PATH}" "${BRANCH}" || exit 0
fi
if [ -x "${REPO_PATH}/.gitqueue.d/update" ]; then
	"${REPO_PATH}/.gitqueue.d/update" "${QUEUE}" "${REPO_PATH}" "${BRANCH}"
else
	_update_repo "${REPO_PATH}" "${BRANCH}"
fi
if [ -x "${REPO_PATH}/.gitqueue.d/run" ]; then
	_nq "${REPO_PATH}/.gitqueue.d/run" "${QUEUE}"
fi

exit 0
