#!/bin/rc
# Copyright 2010 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.

GOROOT=`{basename -d $0}^/..
VERSION=fail

# If hg doesn't work for whatever reason, report failure
if (test -d $GOROOT/.hg && hg version >/dev/null >[2=1]) {
	# Get numerical revision
	VERSION=`{hg identify -n >[2]/dev/null}
	if (~ $status '') {
		OLD=`{hg identify | sed 1q}
		VERSION=`{echo $OLD | awk '{print $1}'}
	}
	
	# Get branch type
	BRANCH=`{hg identify -b >[2]/dev/null}
	switch($BRANCH) {
	case default
		BRANCH=weekly
	case ''
		BRANCH=release
	}
	
	# Find most recent known release or weekly tag.
	TAG=`{hg tags |
		grep $BRANCH |
		sed 's/:.*//' |
		sort -rn -k2 |
		awk -v 'ver='^$VERSION '$2 <= ver && $1~/^(release|weekly)\./ {print $1}' |
		sed -n 1p}
	
	if (! ~ $TAG'')
		VERSION=($TAG $VERSION)
}
	
if (~ $1 -save) {
	if (! ~ $VERSION fail) {
		echo $VERSION >$GOROOT/VERSION
		exit
	}
	echo >[1=2] 'Unable to record version: hg absent'
	exit $VERSION
}

# If a version file created by -save is available, use it
if (test -f $GOROOT/VERSION) {
	cat $GOROOT/VERSION
	exit
}
echo $VERSION
exit
