#!/bin/sh -e

cmd= rmk= expr=
while getopts c:p:k opt; do
	case $opt in
		c) cmd="${OPTARG:?}" ;;
		p) expr="${OPTARG:?}" ;;
		k) rmk=1 ;;
		*) pod2usage --exit=2 "$0"; exit 2 ;;
	esac
done
shift "$((OPTIND-1))"

git-init-db
for tar; do
	find -not -wholename '*/.git*' -delete
	tar --strip-components=1 -xf "$tar"
	mtime=`find -not -wholename '*/.git*' -type f -printf '%T@\n' |sort -u -rn |head -1`
	[ -z "$cmd" ] || eval "$cmd"
	[ -z "$rmk" ] || find -not -wholename '*/.git*' -type f -print0 |xargs -r0 \
		perl -pi -e 's/\$(Date|Header|Id):\s+[^\$]+\$/\$$1\$/&&warn"$ARGV:$.:$&\n"'
	[ -z "$expr" ] || find -not -wholename '*/.git*' -type f -print0 |xargs -r0 \
		perl -pi -e "$expr"
	git-add .
	TZ=UTC faketime -d "1970-01-01 $mtime seconds" -- \
	git-commit -a -m "imported ${tar##*/}"
done
git-repack -a -d
