package BoxPlatform;
use Exporter;
@ISA = qw/Exporter/;
@EXPORT = qw/$build_os $target_os $make_command $bsd_make $platform_define $platform_cpu $gcc_v3 $product_version $product_name $install_into_dir $sub_make_options $platform_compile_line_extra $platform_link_line_extra $platform_lib_files $platform_exe_ext $target_windows/;

BEGIN
{
	# which OS are we building under?
	$target_os = 'netbsdelf-eabihf';
	$target_windows = 0;
	$target_windows = 1 if $target_os =~ m'^mingw32' 
		or $target_os eq "winnt";

	if ($^O eq "MSWin32" and not -x "/usr/bin/uname")
	{
		$build_os = "winnt";
	}
	else
	{
		$build_os = `uname`;
		chomp $build_os;
	}

	# Cygwin Builds usually something like CYGWIN_NT-5.0, CYGWIN_NT-5.1
	# Box Backup tried on Win2000,XP only :)
	$build_os = 'CYGWIN' if $build_os =~ m/CYGWIN/;

	$make_command = 'gmake';

	$bsd_make = 0;

	# blank extra flags by default
	$platform_compile_line_extra = '';
	$platform_link_line_extra = '';
	$platform_lib_files = '-lcrypto -lssl -lz -lexecinfo';
	$platform_exe_ext = '';

	# get version
	my $version_file = "VERSION.txt";
	if (not -r $version_file) { $version_file = "../../$version_file" }
	die "missing version file: $version_file" unless $version_file;

	open VERSION, $version_file or die "$version_file: $!";
	$product_version = <VERSION>;
	chomp $product_version;
	$product_name = <VERSION>;
	chomp $product_name;
	close VERSION;

	if($product_version =~ /USE_SVN_VERSION/)
	{
		# for developers, use SVN version
		my $svnversion = `svnversion .`;
		chomp $svnversion;
		$svnversion =~ tr/0-9A-Za-z/_/c;
		open INFO,'svn info . |';
		my $svnurl;
		while(<INFO>)
		{
			if(m/^URL: (.+?)[\n\r]+/)
			{
				$svnurl = $1
			}
		}
		close INFO;

		my $svndir;
		if ($svnurl =~ m!/box/(.+)$!)
		{
			$svndir = $1;
		}
		elsif ($svnurl =~ m'/(boxi/.+)/boxi/boxbackup')
		{
			$svndir = $1;
		}

		$svndir =~ tr/0-9A-Za-z/_/c;
		$product_version =~ s/USE_SVN_VERSION/$svndir.'_'.$svnversion/e;
	}

	# where to put the files
	$install_into_dir = '/usr/pkg/sbin';

	# if it's Darwin,
	if($build_os eq 'Darwin')
	{
		# see how many processors there are, and set make flags accordingly
		my $cpus = `sysctl hw.ncpu`;
		if($cpus =~ m/hw.ncpu:\s(\d+)/ && $1 > 1)
		{
			print STDERR "$1 processors detected, will set make to perform concurrent jobs\n";
			$sub_make_options = ' -j '.($1 + 1);
		}
		
		# test for fink installation
		if(-d '/sw/include' && -d '/sw/lib')
		{
			print STDERR "Fink installation detected, will use headers and libraries\n";
			$platform_compile_line_extra = '-I/sw/include ';
			$platform_link_line_extra = '-L/sw/lib ';
		}
	}
}

sub make_flag
{
	if($bsd_make)
	{
		return "-D $_[0]"
	}
	return $_[0].'=1';
}

sub parcel_root
{
	my $tos = $_[1] || $target_os;
	return $product_name.'-'.$product_version.'-'.$_[0].'-'.$tos;
}

sub parcel_dir
{
	'parcels/'.parcel_root($_[0], $_[1])
}

sub parcel_target
{
	parcel_dir($_[0]).'.tgz'
}

1;

