#!/bin/sh
set -e

case "$VCS" in
	git)
		if [ -x .git/hooks/pre-commit ]; then
			if ! grep -q "etckeeper pre-commit" .git/hooks/pre-commit; then
				echo "etckeeper warning: .git/hooks/pre-commit needs to be manually modified to run: etckeeper pre-commit -d `pwd`" >&2
			fi
		else
			cat >.git/hooks/pre-commit <<EOF
#!/bin/sh
# pre-commit hook for etckeeper, to store metadata and do sanity checks
set -e
etckeeper pre-commit -d `pwd`
EOF
		chmod +x .git/hooks/pre-commit
		fi
	;;
	hg)
		if [ -e .hg/hgrc ] && grep "^\[hooks\]" .hg/hgrc; then
			if ! grep "^pre-commit" .hg/hgrc | grep -q "etckeeper pre-commit"; then
				echo "etckeeper warning: [hooks] section in .hg/hgrc needs to be manually modified to contain: pre-commit = etckeeper pre-commit -d `pwd`" >&2
			fi
		else
			touch .hg/hgrc
			cat >>.hg/hgrc <<EOF
[hooks]
# pre-commit hook for etckeeper, to store metadata and do sanity checks
pre-commit = etckeeper pre-commit -d `pwd`
EOF
		fi
	;;
	darcs)
		if [ -e _darcs/prefs/defaults ]; then
			if ! ( grep -q "record prehook etckeeper pre-commit" _darcs/prefs/defaults &&
				grep -q "whatsnew prehook etckeeper pre-commit" _darcs/prefs/defaults ); then
				echo "etckeeper warning: _darcs/prefs/defaults needs to be manually modified to run: etckeeper pre-commit -d `pwd`" >&2
			fi
		else
			cat >_darcs/prefs/defaults <<EOF
record prehook etckeeper pre-commit -d `pwd`
record run-prehook
whatsnew prehook etckeeper pre-commit -d `pwd`
whatsnew run-prehook
EOF
		fi
	;;
esac
