#!/usr/bin/env perl
use strict;
#===============================================================================
# Purpose:
#     (a) Build csm_share library
#===============================================================================
my $case = $ENV{CASEROOT};


unshift @INC, "$case/Tools";
require XML::Lite;
require SetupTools;
# Read some xml files for required variables
my %xmlvars = ();
SetupTools::getxmlvars($case, \%xmlvars);
foreach my $attr (keys %xmlvars) {
    $xmlvars{$attr} = SetupTools::expand_env_var($xmlvars{$attr}, \%xmlvars);
}

my $libdir = "$xmlvars{EXEROOT}/csm_share";
chdir($libdir) or die "Could not cd to $libdir: $!\n";


#--------------------------------------------------------------------
# Filepath: list of source code directories (in order of importance).
#--------------------------------------------------------------------
my $comp="mct";
$comp = "esmf" if($xmlvars{USE_ESMF_LIB} eq "TRUE");


my $code = $xmlvars{CODEROOT};

my @filepath = ( "$case/SourceMods/src.share",
		 "$code/drv/shr_$comp",
		 "$code/drv/shr",
		 "$code/dead_share",
		 "$code/csm_share/shr",
		 );
push(@filepath,"$code/utils/esmf_wrf_timemgr") if($comp eq "mct");

my @fp;    
if(-e "Filepath"){
    open(F,"Filepath");
    @fp = <F>;
    close(F);
}

# if the number of lines in @filepath is different than the number of lines in @fp then create a new Filepath file

if($#fp != $#filepath){
    open(F,">Filepath");
    foreach(@filepath){
	print F "$_\n";
    }
    close(F);
}

my $multiinst_cppdefs = "$xmlvars{USER_CPPDEFS}"; 
$multiinst_cppdefs = "$multiinst_cppdefs -DNUM_COMP_INST_ATM=$xmlvars{NINST_ATM}";
$multiinst_cppdefs = "$multiinst_cppdefs -DNUM_COMP_INST_LND=$xmlvars{NINST_LND}";
$multiinst_cppdefs = "$multiinst_cppdefs -DNUM_COMP_INST_OCN=$xmlvars{NINST_OCN}"; 
$multiinst_cppdefs = "$multiinst_cppdefs -DNUM_COMP_INST_ICE=$xmlvars{NINST_ICE}"; 
$multiinst_cppdefs = "$multiinst_cppdefs -DNUM_COMP_INST_GLC=$xmlvars{NINST_GLC}";
$multiinst_cppdefs = "$multiinst_cppdefs -DNUM_COMP_INST_ROF=$xmlvars{NINST_ROF}";

my $bld = "$xmlvars{GMAKE} complib -j $xmlvars{GMAKE_J} MODEL=csm_share COMPLIB=libcsm_share.a USER_CPPDEFS=\" $multiinst_cppdefs\" -f $xmlvars{CASETOOLS}/Makefile ";

my $rc = system($bld);
if($rc==0xff00){
  print "$bld failed with: $!\n";
  exit -2;
}elsif($rc > 0x80){
  $rc >>= 8;
  print "$bld returned non-zero exit status $rc\n";
  exit -3;
}elsif($rc != 0){
  print "$bld ran with ";
  if($rc & 0x80){
	$rc &= ~0x80;
	print "coredump from ";
  }
  print "signal $rc\n";
  exit -4;
}  



system("cp -p -f libcsm_share.a $xmlvars{LIBROOT}/");
system("cp -p -f *.mod $xmlvars{LIBROOT}/include/");