#
#
# Copyright (c) 2014 LIPN - Universite Paris 13
#                    All rights reserved.
#
# This file is part of POSH.
# 
# POSH is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# POSH is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with POSH.  If not, see <http://www.gnu.org/licenses/>.
#
#

#!/usr/bin/perl

use strict;
use warnings;

use Cwd;

my $num_args = $#ARGV + 1;
if ($num_args < 2) {
    print "No input file provided\n";
    exit;
}

my $skip = 0;
my @input_files = ();
my $output_exec="";
my $c = "";
my $no_static = 0;
my $options = "";
my $cur_dir = getcwd;

my $libs="-L. -lshmem -lboost_system";
my $CXX="g++";
my $s2sc="./shmem_s2sc";


# parse args and delete -o <output>
# and all the options
foreach my $arg(@ARGV){
    if( $arg eq '-o' ) {
	# skip this one and tell myself I will need to skip the following one
	$skip = 1;
    } else {
	if( $arg eq "--no-static" ){
	    $no_static = 1;
	} else {
	    $c = substr( $arg, 0, 1 );
	    if( $c eq '-' ) {
		$options = $options . " " . $arg;
		;;
	    } else {
		if( $skip == 0 ) {
		    @input_files = (@input_files, $arg);
		} else {
		    # skip this one too
		    $output_exec=$arg;
		    $skip = 0;
		}
	    }
	}
    }

}

my $filename;
my $command = "";
my $inputfilelist = "";

if( $no_static == 0 ) {
    foreach my $f( @input_files ) {
	$filename = $f;
	$filename =~ s/\//_/g;
	$command = $s2sc . " " . $f . " > /tmp/" . $filename;
	system( $command );
	$inputfilelist =  $inputfilelist . " /tmp/" . $filename;
    } 
} else {
    foreach my $f( @input_files ) {
	$inputfilelist =  $inputfilelist . $f;
    }
}

my $cmdline=$CXX . $options . " -o " . $output_exec . " " . $inputfilelist . " " . $libs . " -I" . $cur_dir;
print $cmdline . "\n";

system( $cmdline );

my $rc = $?;
#exit $rc;

if( $no_static == 0 ) {
    foreach my $f( @input_files ) {
	$filename = $f;
	$filename =~ s/\//_/g;
	$command = "rm /tmp/" . $filename;
	system( $command );
    }
}


exit $rc;
