#!/bin/sh
#
# This scripts adds local version information from the version
# control systems git and mercurial (hg).
#
# If something goes wrong, send a mail the kernel build mailinglist
# (see MAINTAINERS) and CC Nico Schottelius
# <nico-linuxsetlocalversion -at- schottelius.org>.
#
# Based on setlocalversion from Linux kernel
#
#

usage() {
	echo "Usage: $0 [--save-scmversion] [srctree]" >&2
	exit 1
}

save_scm=false
srctree=.
if test "$1" = "--save-scmversion"; then
	save_scm=true
	shift
fi
if test $# -gt 0; then
	srctree=$1
	shift
fi
if test $# -gt 0 -o ! -d "$srctree"; then
	usage
fi

scm_version()
{
	if test -e .scmversion; then
		cat .scmversion
		return
	fi

	# Check for git and a git repo.
	if test -d .git && head=`git rev-parse --verify --short HEAD 2>/dev/null`; then
		date=`git show -s --pretty="%ad" HEAD`

		printf '%s %s%s' "$date" git: $head

		# Is this git on svn?
		if git config --get svn-remote.svn.url >/dev/null; then
			printf -- 'svn:%s' "`git svn find-rev $head`"
		fi

		# Update index only on r/w media
		[ -w . ] && git update-index --refresh --unmerged > /dev/null

		# Check for uncommitted changes
		if git diff-index --name-only HEAD | grep -qv "^scripts/package"; then
			printf '%s' -dirty
		fi

		# All done with git
		return
	fi

	# Check for mercurial and a mercurial repo.
	if test -d .hg && hgid=`hg id 2>/dev/null`; then
		id=`printf '%s' "$hgid" | sed 's/[+ ].*//'`
		date=`hg parents --template "{date|date}"`
		printf '%s %s%s' "$date" hg: "$id"

		# Are there uncommitted changes?
		# These are represented by + after the changeset id.
		case "$hgid" in
			*+|*+\ *) printf '%s' -dirty ;;
		esac

		# All done with mercurial
		return
	fi
}

cd $srctree

# full scm version string
res="$(scm_version)"

if [ "$save_scm" = "true" ]; then
    echo $res > .scmversion
fi

echo "$res"
