#!/usr/bin/perl

use File::Basename;

sub execute_command
{
	print join(' ', @_), "\n";
	if (scalar(@_) > 0) {
		system(@_);		
	} else {
		system($_[0]);				
	}
}

my $infile = $ENV{SCRIPT_INPUT_FILE_1};
my($in_basename, $in_dirname, $in_extension) = fileparse($infile, qr/\.[^.]*/);
my $outdir = "$ENV{DERIVED_FILE_DIR}";
my $perl_wrap_c = "$outdir/${in_basename}_perl_wrap.c";
mkdir "$ENV{OBJECT_FILE_DIR}";
my $perl_wrap_o = "$ENV{OBJECT_FILE_DIR}/${in_basename}_perl_wrap.o";
my $perl_module = "$outdir/${in_basename}.pm";
my $header_paths = "-I'../../../../../debugcore/source' -I'../../../../../DebugBase'";
my $framework_opts = "-F'$ENV{CONFIGURATION_BUILD_DIR}' ";
execute_command("/usr/bin/swig -shadow -perl5 -DHAS_BOOL $header_paths -outdir '$outdir' -o '$perl_wrap_c' '$infile'");

# Get any needed perl options for the next compile
my $ccopts = `perl -MExtUtils::Embed -e ccopts`;
my $libperl_dir = undef;
if ($ccopts =~ /-I(\/System.*CORE)/)
{
	 $libperl_dir = $1;
	 print "libperl directory: '$libperl_dir'\n";
}

execute_command("cd '$ENV{OBJECT_FILE_DIR}' && ln -s '$libperl_dir/libperl.dylib'");


# Strip out the default architectures it gave us, we will add them back with
# the $arch_opts below
$ccopts =~ s/-arch [a-z_0-9]+//g;

# Get a list of our build architectures
my $arch_opts = "-arch " . join(' -arch ', split('\s+', $ENV{ARCHS}));

execute_command("gcc -c -Dbool=char $arch_opts $ccopts $header_paths $framework_opts -I'$ENV{PROJECT_DIR}/source' '$perl_wrap_c' -o '$perl_wrap_o'");

execute_command("cp '$perl_module' '$ENV{CONFIGURATION_BUILD_DIR}/$ENV{SHARED_SUPPORT_FOLDER_PATH}'");