#! /usr/bin/env perl

use File::Basename;
use strict;
use warnings;

my @default_paths = (
	"/bin",
	"/usr/bin",
	"/usr/local/bin",
	"/opt/local/bin",   # Mac.  Think different.
);

# return undef if not found, or a path if found and better than 2.8.3.
sub find_cmake
{
	my $cmake;
	my $cmake_ver;
	my @ver;
	my $path;
	my @dpaths;

	@dpaths = @default_paths;

	# If a cmake is present, put it to the front of the paths to check
	# to ensure it is of the correct version.
	$cmake = `which cmake 2>&1`;
	if ($? == 0) {
		chomp $cmake;
		if ($cmake !~ m/^which:/) {
			unshift @dpaths, dirname($cmake);
		}
	}

	# check the versions of cmake found, if any.
	foreach $path (sort @dpaths) {
		if ( -f "$path/cmake" ) {
			$cmake = "$path/cmake";
			$cmake_ver = `$cmake --version 2>&1`;
			chomp $cmake_ver;
			$cmake_ver =~ s/cmake version //g;
			@ver = split /\./, $cmake_ver;

			# If the version is better than 2.8.3 (the minimal version of
			# cmake) for which Condor is known to build, return it.
			if (($ver[0] > 2) ||
				($ver[0] == 2 && $ver[1] > 8) ||
				($ver[0] == 2 && $ver[1] == 8 && $ver[2] >= 3))
			{
				return $cmake;
			}
		}
	}

	# otherwise, found nothing
	return undef;
}

sub find_wget
{
	my $path;

	$path=`which wget 2>&1`;
	if ($? != 0) {
		foreach $path (sort @default_paths) {
			if ( -f "$path/wget" ) {
				return "$path/wget";
			}
		}
		return undef;
	}

	chomp $path;
	return $path;
}

sub install_cmake
{
	my ($ename, $iloc) = (@_);
	my ($cmake, $wget);

	$cmake = find_cmake();
	if (defined($cmake)) {
		return $cmake;
	}

	$wget = find_wget();

	system("$wget -r http://parrot.cs.wisc.edu/externals/$ename.tar.gz -O $ename.tar.gz");
	if ($? != 0) {
		die "FAILURE: Couldn't download cmake-2.8.3: $!\n";
	}

	system("tar zxf $ename.tar.gz");
	if ($? != 0) {
		die "FAILURE: Couldn't untar cmake-2.8.3: $!\n";
	}

	system("cd $ename && (./bootstrap --prefix=\"$iloc\" ; make ; make install)");
	if ($? != 0) {
		die "FAILURE: Couldn't bootstrap; make; make install cmake-2.8.3: $!\n";
	}

	return "$iloc/bin/cmake";
}

sub main
{
	my $iloc;
	my $path_to_cmake;

	$iloc = shift @ARGV || `pwd`;
	chomp $iloc;
	$iloc .= "/local";

	# This will either find the right version of cmake or download it and
	# install it and return the path to the bin directory.
	$path_to_cmake = install_cmake("cmake-2.8.3", $iloc);

	printf "SUCCESS: $path_to_cmake\n";
	return 0;
}

exit main();


