#!/bin/sh
#
# Copyright (c) 2025-2026 Jacob Edwards <jacob@jacobedwards.org>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIE
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

set -e

log() {
	echo "$(basename "$0"): $@" 1>&2
}

err() {
	log "$@"
	exit 1
}

loadconfig() {
	if test -f "$rc"
	then
		while read -r key val
		do
			case $key in
			(stagit) stagit="$val" ;;
			(distdir) distdir="$val" ;;
			(distfmt) distfmt="$val" ;;
			(ghtoken) ghtoken="$val" ;;
			(mandir) mandir="$val" ;;
			(pubfile) pubfile="$val" ;;
			(*) err 'Invalid configuration'
			esac
		done < "$rc"
	fi
}

update() {
	IFS='
'
	public="$(find "$@" -maxdepth 1 -name "$pubfile" | awk -F/ -vOFS=/ '{$NF="";print}')"

	test "$stagit" '=' 'true' && {
		log "Generating stagit pages"
		stagit-hook $public
	}
	test -n "$distdir" && {
		log "Creating tag archives"
		gitdist -a ${distfmt:+-f "$distfmt"} -o "$distdir" $public
	}
	test -n "$mandir" && {
		log "Exporting manpages"
		gitman -d "$mandir" $public
	}
	test -n "$ghtoken" && {
		log "Mirroring to GitHub"
		github-mirror -t "$ghtoken" "$@"
	}
}

pubfile=git-daemon-export-ok
rc=/etc/gitsrv.conf
loadconfig

err="$(mktemp -t gitsrv-errXXXXXX)"
trap 'rm -f "$err"' EXIT

# Can't use "${@:-"$GIT_DIR"}" because empty GIT_DIR runs
# with empty string instead of just indexing like it should
test $# -eq 0 -a -n "$GIT_DIR" &&
	set -- "$GIT_DIR"
unset GIT_DIR

{
	update "$@"
} > "$err" 2>&1 || {
	logger -st gitsrv -p error < "$err"
	exit 1
}
