#! /usr/bin/env perl
use strict;
use File::Compare;

if ($#ARGV == -1) {
    die " ERROR clm.buildlib: must specify at least a caseroot input argument";
}
my ($CASEROOT, $bldpath, $phys) = @ARGV;
chdir "$CASEROOT";

my $CASEBUILD = `./xmlquery CASEBUILD -value`;
my $CASETOOLS = `./xmlquery CASETOOLS -value`;
my $OBJROOT   = `./xmlquery OBJROOT   -value`;
my $LIBROOT   = `./xmlquery LIBROOT   -value`;
my $GMAKE_J   = `./xmlquery GMAKE_J   -value`;
my $GMAKE     = `./xmlquery GMAKE     -value`;

if (! defined($phys)){
    $phys = 'lnd';
    $bldpath = $OBJROOT;
} 
chdir "$bldpath/$phys/obj";

if (-f "$CASEBUILD/clmconf/Filepath") {
    my $sysmod = "cp $CASEBUILD/clmconf/Filepath ./tmp_filepath ";
    system($sysmod) == 0 or die "ERROR: clm.buidlib $sysmod failed: $?\n";
} else {
    die "ERROR clm.buildlib  - missing $CASEBUILD/clmconf/Filepath";
}

foreach my $file ( "Filepath", "CESM_cppdefs" ) {
    if (-f "$CASEBUILD/clmconf/$file") {
	my $sysmod = "cp $CASEBUILD/clmconf/$file ./tmp_$file";
	system($sysmod) == 0 or die "ERROR: clm.buidlib $sysmod failed: $?\n";
    } else {
	die "clm.buildlib ERROR - missing $CASEBUILD/clmconf/$file"
    }
    if (-f "$file") {
	if (compare("tmp_$file", "$file") != 0) {
	    my $sysmod = "mv -f tmp_$file $file ";
	    system($sysmod) == 0 or die "ERROR: clm.buidlib $sysmod failed: $?\n";
	}
    } else {
	my $sysmod = "mv -f tmp_$file $file";
	system($sysmod) == 0 or die "ERROR: clm.buidexe $sysmod failed: $?\n";
    }
}

my $clmdefs = `cat $CASEBUILD/clmconf/CESM_cppdefs`;
chomp($clmdefs);
my $sysmod = "$GMAKE complib -j ${GMAKE_J} MODEL=clm COMPLIB=${bldpath}/lib/lib${phys}.a USER_CPPDEFS=\"${clmdefs}\" -f ${CASETOOLS}/Makefile";
system($sysmod) == 0 or die "ERROR: clm.buildlib $sysmod failed: $?\n";

exit(0);



