#!/usr/bin/env bash
#
# Common code shared by the Cogito toolkit.
# Copyright (c) Petr Baudis, 2005
#
# This file provides a library containing common code shared with all the
# Cogito programs.

_cg_cmd=${0##*/}

_git=.git
_git_objects=${SHA1_FILE_DIRECTORY:-$_git/objects}


die () {
	echo $_cg_cmd: $@ >&2
	exit 1
}


mktemp () {
	if [ ! "$BROKEN_MKTEMP" ]; then
		$(which mktemp) "$@"
		return
	fi

	dirarg=
	if [ x"$1" = x"-d" ]; then
		dirarg="-d"
		shift
	fi
	prefix=
	if [ x"$1" = x"-t" ]; then
		prefix=${TMPDIR:-/tmp}/
		shift
	fi

	$(which mktemp) $dirarg $prefix"$1"
}


showdate () {
	date="$1"
	sec=${date[0]}; tz=${date[1]}
	dtz=${tz/+/}
	lsec=$(expr $dtz / 100 \* 3600 + $dtz % 100 \* 60 + $sec)
	pdate="$(date -Rud "1970-01-01 UTC + $lsec sec" 2>/dev/null)"

	echo "${pdate/+0000/$tz}"
}


print_help () {
	which "cg-$1" >/dev/null 2>&1 || exit 1
	cat $(which cg-$1) | sed -n '3,/^$/s/^# *//p'
	exit
}

for option in "$@"; do
	if [ "$option" = "-h" -o "$option" = "--help" ]; then
		print_help ${_cg_cmd##cg-}
	fi
done


# Compatibility hacks:
# 2005-04-26
if [ -d $_git ] && [ -s $_git/remotes ] && [ ! -e $_git/branches ]; then
	stop=
	mkdir $_git/branches || stop=1
	[ "$stop" ] || cat $_git/remotes | while read branch location; do
		echo "$location" >$_git/branches/$branch
	done || stop=1
	[ "$stop" ] || rm $_git/remotes
fi
# 2005-04-26
if [ -d $_git ] && [ ! -d $_git/refs ]; then
	stop=
	mkdir $_git/refs || stop=1
	if [ ! "$stop" ]; then
		mv $_git/heads $_git/refs
		mv $_git/tags $_git/refs
		tgt=$(readlink $_git/HEAD)
		if [ "$tgt" ]; then
			rm $_git/HEAD
			ln -s "refs/$tgt" $_git/HEAD
		fi
	fi
fi


export BROKEN_MKTEMP=1
del=$($(which mktemp) -t 2>/dev/null) && { rm $del; export BROKEN_MKTEMP=; }
