use alienfile;

use Config;
use File::Spec;

# NOTE: you can set ALIEN_CMAKE_FROM_SOURCE to force a build from source
# even on platforms which have binary versions of cmake available.  Normally
# you should only need this for testing the build from source capability of
# this alienfile.

plugin 'Probe::CommandLine' => (
	command => 'cmake',
	args => ['--version'],
	match => qr/^cmake\s+version\s+4\.[0-9\.]+/m,
	version => qr/^cmake\s+version\s+(4\.[0-9\.]+)/,
);

share {
	my $binary_release_name;
	my $binary_format;
	if ($^O eq 'linux' && $Config{'archname'} =~ /^x86_64/) {
		$binary_release_name = 'linux-x86_64';
		$binary_format = 'tar.gz';
	} elsif ($^O eq 'linux' && $Config{'archname'} =~ /^aarch64/) {
		$binary_release_name = 'linux-aarch64';
		$binary_format = 'tar.gz';
	} elsif ($^O eq 'MSWin32' && $Config{'ptrsize'} == 4) {
		$binary_release_name = 'windows-i386';
		$binary_format = 'zip';
	} elsif ($^O eq 'MSWin32' && $Config{'ptrsize'} == 8) {
		$binary_release_name = 'windows-x86_64';
		$binary_format = 'zip';
	} elsif ($^O eq 'darwin' && $Config{'ptrsize'} == 8) {
		my ($major, $minor, $patch) = map {
			my $v = $_;
			$v =~ s/^\s+//;
			$v =~ s/\s+$//;
			$v;
		} split /\./, [split /:/, `sw_vers|grep ProductVersion`]->[1];
		if ($major >= 11 || ($major == 10 && $minor >= 13)) {
			$binary_release_name = 'macos-universal';
		} else {
			$binary_release_name = 'macos10.10-universal';
		}
		$binary_format = 'tar.gz';
	}

	# For platforms where there is a binary release, use that:
	if ($binary_release_name && ! $ENV{ALIEN_CMAKE_FROM_SOURCE}) {
		start_url 'https://cmake.org/files/v4.3';
		plugin Download => (
			filter	=> qr/^cmake-4\.[0-9\.]+-\Q$binary_release_name\E\.\Q$binary_format\E$/,
			version => qr/([0-9\.]+)/,
			($^O eq 'MSWin32' ? (bootstrap_ssl => 1) : ()),
		);
		plugin Extract => $binary_format;
		if ($^O eq 'MSWin32') {
			build sub {
				my $build = shift;
				# This is a rare case where we actually want the borked windows
				# type paths with backslashes.
				my $stage = File::Spec->catdir($build->install_prop->{stage});
				path($stage)->mkpath unless -d $stage;
				$build->system("xcopy . $stage /E");
			};
		} elsif ($^O eq 'darwin') {
			build [
				'cp -a CMake.app/Contents/* %{.install.stage}',
				sub { shift->runtime_prop->{style} = 'binary' },
			];
		} else {
			build [
				'cp -ar * %{.install.stage}',
				sub { shift->runtime_prop->{style} = 'binary' },
			];
		}

	# For platforms without a (recent) binary release, build it from source.
	} else {
		start_url 'https://cmake.org/download/';
		plugin Download => (
			filter	=> qr/^cmake-4\.[0-9\.]+\.tar.gz$/,
			version => qr/([0-9\.]+)/,
		);
		plugin Extract => 'tar.gz';
		plugin 'Build::Autoconf' => ('with_pic' => 0);
		build [
			'%{configure}',
			'%{make}',
			'%{make} install',
			sub { shift->runtime_prop->{style} = 'source' },
		];
	}

	after 'gather' => sub {
		my $build = shift;

		$build->runtime_prop->{'command'} = 'cmake';
        };
};
