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

setenv PIO_DIR $CCSMROOT/models/utils/pio   # pio directory
setenv PIO_LIBDIR $EXEROOT/pio

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 ${PIO_LIBDIR}

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

endif

if (${suitecopy} != true) then

  echo "Copying source to CCSM EXEROOT..."

  cd $PIO_LIBDIR
  cp -p $PIO_DIR/Makefile .

  set runconf = 0
  set runclean = 0

# It would be harmless to just run "configure" each time but it
# takes time so use file "pio_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 pio_conf) then
    echo "PIO already built. Checking machine type"
    cp -f pio_conf pio_conf.old
    echo ${MACH} > pio_conf
    set diffwc = 1
    set diffwc = `diff pio_conf.old pio_conf | wc -m`
    if ($diffwc != 0) then
      echo "Different machine. Rerun configure"
      rm Makefile.conf.old
      rm -f $LIBROOT/libpio.a
      set runconf = 1
      set runclean = 1
    else
      echo "Same machine."
      cp -p Makefile.conf.old Makefile.conf
    endif
  else
    echo "New build of PIO"
    echo ${MACH} > pio_conf
    set runconf = 1
  endif

# run configure with correct arguments if necessary
  set preconf = $CASETOOLS/pio.Makefile.conf.$MACH
  if ($runconf == 1) then
    if (-e $preconf && $MPILIB == "mpi-serial") then
       # assuming pre-made Makefile.conf files are NOT good for MPISERIAL
       echo "Using $preconf configure file"
       cp -p $preconf Makefile.conf
    else
       echo "Running configure..."
       echo "for OS=$OS MACH=$MACH"
       $GMAKE -f $CASETOOLS/Makefile $PIO_LIBDIR/Makefile.conf MODEL=pio
    endif
  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 ${PIO_LIBDIR} ${suitedir}/
  endif


endif

  cp -p libpio.a $LIBROOT/
  cp -p *.mod $LIBROOT/include/

exit 0
