#!/bin/sh

set -e

err() {
	echo "$@" 1>&2
	exit 1
}

# This should be more flexible, but it works for now.
hooked() (
	cd "$repodir"
	ls -d */"$hasfile" | awk -F/ '{print $1}' |
		while read dir
	do
		git --git-dir "$dir" show -s --format="%ct	$dir" ||
			err "$dir: Unable to get repo information"
	done | sort -rn | cut -f2- | sed "i\\
${repodir%/}/"
)

loadfile() {
	case "$1" in
	(link) ;;
	(copy) link=false ;;
	(*) err "$1: link or copy"
	esac
	test "$2" -ef "$3" ||
	    ${link:-ln -f "$2" "$3"} ||
	    cat "$2" > "$3"
}

loadstyle() {
	c="${1:?requried}"
	s="$2"
	d="${3:-.}"

	for f in style.css logo.png favicon.png
	do
		loadfile "$c" "$s/$f" "$d/$f"
	done
}

index() (
	IFS='
'
	test -n "$styledir" && loadstyle copy "$styledir" "$basedir"
	stagit-index $(hooked) > "$basedir"/index.html
)

repo() {
	abs="$(readlink -f "$1")"
	nam="$(basename "$abs")"
	dir="$basedir"/"$nam" 
	mkdir -p "$dir"
	cd "$dir"
	test -n "$styledir" && loadstyle link ..
	stagit -u "$baseurl" "$abs"
}

loadconfig() {
	if test -f "$rc"
	then
		while read key val
		do
			case $key in
			(basedir) basedir="$val" ;;
			(baseurl) baseurl="$val" ;;
			(repodir) repodir="$val" ;;
			(hasfile) hasfile="$val" ;;
			(styledir) styledir="$val" ;;
			(*) err 'Invalid configuration'
			esac
		done < "$rc"
	fi
}

rc=/etc/stagit-hook
host="$(hostname)"
basedir=/var/www/htdocs/"$host"/projects/
baseurl=https://"$host"/projects/
repodir="$HOME"
hasfile=refs

loadconfig

err="$(mktemp -t stagit-hook-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
	index
	for d in "$@"
	do
		repo "$d" || {
			status=$?
			echo "$d: Unable to generate" 1>&2
		}
	done
{
	exit $status
} > "$err" 2>&1 || {
	logger -st stagit-hook -p error < "$err"
	exit 1
}
