#! /bin/csh -f
#==============================================================================
# Purpose:
#     (a) Build mct library
#==============================================================================

setenv MCT_DIR $CCSMROOT/models/utils/mct   # mct directory
setenv MCT_LIBDIR $EXEROOT/mct

set suite = false
set suitecopy = false
if ($?SUITEFLAGID) then
  set suite = true
  set suitedir = $RUNDIR/../../libs.${SUITEFLAGID}.${SMP_VALUE}.${DEBUG}
  mkdir -p ${suitedir}
  mkdir -p ${MCT_LIBDIR}

  if (-e ${suitedir}/mct) then
    set suitecopy = true
    cp -p -r ${suitedir}/mct/* ${MCT_LIBDIR}/
    echo "Reusing mct build from ${suitedir}"
  endif
endif

if (${suitecopy} != true) then

  cd $MCT_LIBDIR
  echo "Copying source to CCSM EXEROOT..."
#  cp -r -p $MCT_DIR/* .
  cp $MCT_DIR/Makefile .
  mkdir mct
  cp $MCT_DIR/mct/Makefile mct
  mkdir mpeu
  cp $MCT_DIR/mpeu/Makefile mpeu
  mkdir mpi-serial
  cp $MCT_DIR/mpi-serial/Makefile mpi-serial

  set runconf = 0
  set runclean = 0

# It would be harmless to just run "configure" each time but it
# takes time so use file "mct_conf" to determine if configure must
# be run.  There are three possibilities:
# 1. brand new build -- run configure
# 2. already built but platform has changed (this can happen
#    when a filesystem is mounted on multiple platforms) -- run configure
# 3. already built, same platform -- don't run configure
#
  if(-e mct_conf) then
    echo "MCT already built. Checking machine type"
    cp -f mct_conf mct_conf.old
    echo ${OS} > mct_conf
    set diffwc = 1
    set diffwc = `diff mct_conf.old mct_conf | wc -m`
    if ($diffwc != 0) then
      echo "Different machine. Rerun configure"
      rm Makefile.conf.old
      rm -f $LIBROOT/libmct.a
      rm -f $LIBROOT/libmpeu.a

      set runconf = 1
      set runclean = 1
    else
      echo "Same machine."
      cp -p Makefile.conf.old Makefile.conf
    endif
  else
    echo "New build of MCT"
    echo ${OS} > mct_conf
    set runconf = 1
  endif

# run configure with correct arguments if necessary
  if ($runconf == 1) then
    echo "Running configure..."
    echo "for OS=$OS MACH=$MACH"
    $GMAKE -f $CASETOOLS/Makefile $MCT_LIBDIR/Makefile.conf 
  endif

  if ($runclean == 1) then
    $GMAKE clean
  endif

  cp -p Makefile.conf Makefile.conf.old

  $GMAKE || exit 1

  if (${suite} == true) then
    cp -p -r ${MCT_LIBDIR} ${suitedir}/
  endif

endif

  cp -p mct/lib*.a $LIBROOT/
  cp -p mpeu/lib*.a $LIBROOT/
  if (-d mpi-serial) cp -p mpi-serial/lib*.a $LIBROOT
  cp -p mct/*.mod $LIBROOT/include/
  cp -p mpeu/*.mod $LIBROOT/include/

exit 0

