#!/usr/pkg/bin/bash
#
# Export contents of a particular revision
# Copyright (c) Johannes E. Schindelin, 2005
#
# Takes a destination and optionally a tree ID as a parameter,
# defaulting to 'HEAD'.
#
# The destination can be either a `.tar`, `.tar.gz`, `.tar.bz2` or `.tgz`
# for generating a tarball. Other destination specifiers are assumed
# to be directory names, and the tree is exported to the given directory.
#
# OPTIONS
# -------
# -r TREE_ID:: Specify the tree version to export
#	Base the export on the given tree.

# Testsuite: TODO

USAGE="cg-export [-r TREE_ID] DESTFILE"
_git_requires_root=1
_git_wc_unneeded=1

. "${COGITO_LIB:-/usr/pkg/lib/cogito/}"cg-Xlib || exit 1

id=
while optparse; do
	if optparse -r=; then
		# We do not resolve to tree id since git-tar-tree can
		# utilize some commit information.
		id="$(cg-object-id -c "$OPTARG" 2>/dev/null)" || id="$OPTARG"
	else
		optfail
	fi
done

if [ -z "$id" ]; then
	id="$(cg-object-id -c)"
fi

dest="${ARGS[0]}"

([ -n "$dest" ] && [ -n "$id" ]) || usage

[ -e "$dest" ] && die "$dest already exists."

case "$dest" in
	*.tar|*.tar.gz|*.tar.bz2|*.tgz)
		base="${dest%.tar*}"
		base="${base%.tgz}"
		ext="${dest#$base}"
		base="${base##*/}"
		case "$ext" in
		.tar.gz|.tgz)
			git-tar-tree "$id" "$base" | gzip -c9 >"$dest"
			;;
		.tar.bz2)
			git-tar-tree "$id" "$base" | bzip2 -c >"$dest"
			;;
		.tar)
			git-tar-tree "$id" "$base" >"$dest"
			;;
		esac
		;;
	*)
		mkdir -p "$dest" || die "cannot create $dest"
		export GIT_INDEX_FILE="$dest/.git-index"
		id="$(cg-object-id -t "$id")"
		git-read-tree "$id"
		git-checkout-index "--prefix=$dest/" -a
		rm "$GIT_INDEX_FILE"
	;;
esac
