#!/bin/sh
# generic git post-receive hook.
#
# if name is not set the basename of the current directory is used,
# this is the directory of the repo when called from the post-receive script.

# NOTE: needs to be set for correct locale (expects UTF-8) otherwise the
#       default is LC_CTYPE="POSIX".
export LC_CTYPE="en_US.UTF-8"
export PATH="/home/private/stagit/bin:$PATH"

name="$1"
if test "${name}" = ""; then
	name=$(basename "$(pwd)")
fi

reposdir="/home/public/git"
dir="${reposdir}/${name}"

if ! test -d "${dir}"; then
	echo "${dir} does not exist" >&2
	exit 1
fi
cd "${dir}" || exit 1

# detect git push -f
force=0
while read -r old new ref; do
	test "${old}" = "0000000000000000000000000000000000000000" && continue
	test "${new}" = "0000000000000000000000000000000000000000" && continue

	hasrevs=$(git rev-list "${old}" "^${new}" | sed 1q)
	if test -n "${hasrevs}"; then
		force=1
		break
	fi
done

printf "[%s] stagit HTML pages... " "${name}"

# remove commits on git push -f
if test "${force}" = "1"; then
	rm -rf "commit"
fi

stagit-index "${reposdir}/"*/ > "${reposdir}/index.html"
stagit -l 100 -u "https://riazj.com/git/${name}/" "${dir}"

ln -sf log.html index.html
ln -sf ../style.css style.css

echo "done"
