// Copyright (c) 2010, Jens Peter Secher <jpsecher@gmail.com>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

// This implementation was inspired by John Goerzen's hg-markdeb.

class MercurialTagVersion
{
	public static function main()
	{
		logger = new Script();
		var usage = "Usage: " + Constants.tagVersion() + " [-V|--version]" +
			" [-v|--verbose] [-i|--ignore-uncommitted] [-f|--force]\n";
		var options = new GetPot( Sys.args() );
		Util.maybeReportVersion( options, usage );
		// Collect verbosity options.
		while( options.got( ["--verbose","-v"] ) ) ++logger.verbosity;
		// Should uncommitted changes be ignored?
		var ignore = options.got( ["-i","--ignore-uncommited"] );
		// Should the tag overwrite?
		var force = options.got( ["-f","--force"] );
		// Reject other arguments.
		Util.exitOnExtraneousArguments( options, usage );
		// Extract package information from the changelog file.
		var changeLog = DebianChangeLog.parseCurrentChangeLog( logger );
		// Check for presence of Mercurial directory.
		Mercurial.exitIfNoWorkingDirectory( "." );
		// Complain if working directory is not clean.
		if( Mercurial.uncommittedChanges( logger ) )
		{
			if( ! ignore )
			{
				Util.die( "Working directory has uncommitted changes." );
			}
			logger.info( 1, "Ignoring uncommited changes." );
		}
		// Construct a tag for the current revision.
		var newTag = Util.fullTag( changeLog );
		// Complain if the tag is already there.
		if( Mercurial.hasTag( newTag, logger ) )
		{
			if( ! force )
			{
				Util.die( "Tag " + newTag + " already exists." );
			}
			logger.info( 1, "Overwriting tag " + newTag + "." );
		}
		// Let Mercurial do the tag.
		var msg = Constants.tagVersion() + " added tag " + newTag;
		Process.runButExitOnError( "hg", [ "tag", newTag, "-f", "-m", msg ], logger );
	}

	static var logger : Script;
}
