#!/usr/bin/env bash
#
# Normalize an ID to an SHA1 hash value.
# Copyright (c) Petr Baudis, 2005
# Copyright (c) Philip Pokorny, 2005
#
# Strings resolve in this order:
# 	NULL, this, HEAD  => .git/HEAD
# 	<tags>
# 	<heads>
# 	short SHA1 (4 or more hex digits)
#
# Takes the ID to normalize and returns the normalized ID.

. ${COGITO_LIB}cg-Xlib

id="$1"

if [ ! "$id" ] || [ "$id" = "this" ] || [ "$id" = "HEAD" ]; then
	read id < "$_git/HEAD"

elif [ -r "$_git/refs/tags/$id" ]; then
	read id < "$_git/refs/tags/$id"

elif [ -r "$_git/refs/heads/$id" ]; then
	read id < "$_git/refs/heads/$id"

# Short id's must be lower case and at least 4 digits.
elif [[ "$id" == [0-9a-z][0-9a-z][0-9a-z][0-9a-z]* ]]; then
	idpref=${id:0:2}
	idpost=${id:2}

	# Assign array elements to matching names
	idmatch=($_git_objects/$idpref/$idpost*)

	if [ ${#idmatch[*]} -eq 1 ] && [ -r "$idmatch" ]; then
		id=$idpref${idmatch#$_git_objects/$idpref/}
	elif [ ${#idmatch[*]} -gt 1 ]; then
		echo "Ambiguous id: $id" >&2
		exit 1
	fi
fi

if ([ "$id" ] && [ "$id" != " " ]) && ([ ${#id} -ne 40 ] || [ ! -f .git/objects/${id:0:2}/${id:2} ]); then
	reqsecs=$(date --date="$id" +'%s' 2>/dev/null)

	if [ "$reqsecs" ]; then
		id=$(git-rev-list --min-age=$reqsecs --max-count=1 HEAD)
	fi
fi

# If we don't have a 40-char ID by now, it's an error
if [ ${#id} -ne 40 ] || [ ! -f $_git_objects/${id:0:2}/${id:2} ]; then
	echo "Invalid id: $id" >&2
	exit 1
fi

if [ "$(git-cat-file -t "$id")" = "tag" ]; then
	id=$(git-cat-file tag "$id" | head -n 1)
	id="${id#object }"
fi

echo $id
