#! /usr/bin/perl

sub cabal_unpack
{
	$pkg = shift;
	`mkdir -p tmp-export ; cd tmp-export ; cabal unpack ${pkg} 2>\&1 | grep -i unpacking` =~ /[ "]+([^ "]+)(\.\.\.|\/)/;
	$unpackdir = "tmp-export/$1";
	`cd ${unpackdir} ; cabal configure ; cabal haddock --hoogle`;
	return $unpackdir;
}

$num_args = @ARGV;

if ($num_args == 2) {
	$recent_dir = &cabal_unpack($ARGV[0]);
	$old_dir = &cabal_unpack($ARGV[1]);
} else {
	# If one argument given, compare current directory:
	$recent_dir = ".";
	`cabal configure ; cabal haddock --hoogle`;
	$old_dir = &cabal_unpack($ARGV[0]);
}

for $dir ($recent_dir, $old_dir)
{
	$filename = "${dir}/.tmp-export";
	open FILE, "> ${filename}";
	$module = "";
	for $line (`grep -v "^--" ${dir}/dist/doc/html/*/*.txt | grep -v "^\\s*\$"`)
	{
		if ($line =~ /^module (.+)$/) {
			$module = $1 . ":";
		} else {
			print FILE "${module}${line}";
		}
	}
	close FILE;
	`sort ${filename} > ${filename}-sort`;
}

@output = `diff ${old_dir}/.tmp-export-sort ${recent_dir}/.tmp-export-sort`;
print @output;

$instances_changed = 0;
$changed_or_removed = 0;
$something_added = 0;
for $line (@output)
{
	if ($line =~ /\@version/) {
		#Not important to us
	} elsif ($line =~ /:instance/) {
		$instances_changed = 1;
	} elsif ($line =~ /^\<.*/) {
		$changed_or_removed = 1;
	} elsif ($line =~ /^\>.*/) {
		$something_added = 1;
	}
}

print "\nGiven previous version number A.B.C.D:\n";
if ($instances_changed) {
	print "It seems you have added, removed or changed some instances.  You must increase A or B\n";
}
if ($changed_or_removed) {
	print "It seems you have removed something, or changed its name or type.  You must increase A or B\n";
}
if ($something_added) {
	print "It seems you have added something.  You must increase C (or A or B)\n";
}
unless ($instances_changed or $changed_or_removed or $something_added) {
	print "You don't appear to have changed any of the API.  If this is a bug fix, you can just increase D.  If you have changed any behaviour, it is best to increase at least C\n";
}
