#!/bin/bash
#
#   Usage: build-nemo-rtd [options] ver=tag exec=name type=rtdtype \
#                     [repo=dirpath] \
#          Quantities in square brackets are optional
#
# Purpose: Create a nemo-rtd executable 
#
# Options:
# All options begin with a dash (-) and must appear before any other command line arg
# Single letter options may be combined, as in "build-nemo -vv ..."
#   -h   ...show this usage message
#   -k   ...do not delete the tmp dir after compilation is complete (used for debugging)
#
# Variable definitions:
#   ver=tag       ...tag is the version number/tag or branch to extract from
#                    the git repository (e.g. nemo_v3.4)
#   exec=name     ...name is the name of the nemo executable to be created
#                    On successful compilation, a file by this name will be saved on RUNPATH
#   type=rtdtype  ...either 'carbon-pisces', 'carbon-cmoc', 'ice' or 'physical', depending on which 
#                    type or rtd is to be built.
#
#   repo=dirpath  ...dirpath is the pathname to the git repository
#
# Examples:
#
#   build-nemo-rtd type=physical ver=ccc-nemo-0.1 exec=uncs_nemo_physical_rtd_ccc-nemo-0.1_exe 
#     -- Build a physical rtd executable from the central nemo-cccma repo using the ccc-nemo-0.1 branch.
#
#   build-nemo-rtd type=carbon-pisces repo=/users/tor/acrn/ncs/nemo_repo_2/ ver=rtd exec=test_nemo_carbon_rtd_exe 
#     -- Build a carbon-pisces rtd executable from a custom local repo (/users/tor/acrn/ncs/nemo_repo_2/) and branch (rtd).
#
########################################################################
#
# Neil Swart Sep 2014, based on build-nemo by Larry Solheim Sep 2012

FULLPATH=`type $0|awk '{print $3}'` # pathname of this script
Runame=`basename $FULLPATH`
usage() {
  err_exit=0
  while getopts e opt; do
    case $opt in
      e) err_exit=1 ;;
    esac
  done
  shift `expr $OPTIND - 1`

  [ -n "$1" ] && echo >&2 "${Runame}:" "$@"
  echo >&2 " "
  sed >&2 -n '/^###/q; s/^#$/# /; s/^ *$/# /; 3,$s/^# //p;' "$FULLPATH"
  if [ $err_exit -eq 0 ]; then
    exit
  else
    exit 1
  fi
}

# Create time stamp to be used in file names etc
stamp=`date "+%j%H%M%S"$$`

# Identify, by name, the machine this script is running on
this_host=`hostname|cut -d'.' -f1`

bail(){
echo "${Runame}: *** ERROR *** $1"
exit 1
}

add2path(){
  if echo $PATH|/bin/grep -Evq "'(^|:)'$1'($|:)'" ; then
     if [ "$2" = "atend" ] ; then
        PATH=$PATH:$1
     else
        PATH=$1:$PATH
     fi
  fi
}

# echo without return (ie: emulate -n if not recognized by echo)
if [ "X`echo -n`" = "X-n" ]; then
  echo_n() { echo ${1+"$@"}'\c'; }
else
  echo_n() { echo -n ${1+"$@"}; }
fi

# Set defaults

# The version of code to extract and compile
nemo_version=''

# The default location of the repository containing nemo source code
[ -z "$CCRNSRC" ] && bail "CCRNSRC must be set"
[ ! -d "$CCRNSRC" ] && bail "CCRNSRC=$CCRNSRC is not a directory"
nemo_source_repo=$CCRNSRC/ocean_dir/nemo-CCCma.git

# The name of the executable created by this script
nemo_rtd_exe=''

# A boolean flag used to build (or not build) the nemo executable
build_nemo_rtd_exe=1

# Verbosity flag
verbose=0

# Flag to remove, or not remove, temporary dir created below
keep_tmpd=0

# CCRNSRC must be defined
CCRNSRC=${CCRNSRC:=/home/acrnsrc}
[   -z "$CCRNSRC" ] && bail "CCRNSRC must be defined"
[ ! -d "$CCRNSRC" ] && bail "$CCRNSRC is not a directory"

# CCRNTMP must be defined
CCRNTMP=${CCRNTMP:=/tmp}
[   -z "$CCRNTMP" ] && bail "CCRNTMP must be defined"
[ ! -d "$CCRNTMP" ] && bail "$CCRNTMP is not a directory"

# process command line options
while getopts hkx opt
do
  case $opt in
    k) keep_tmpd=1 ;;
    x) set -x ;;
    h) usage ;;
    -) shift; break ;; # end of options
    ?) usage -e $USAGE   ;;
  esac
done
shift `expr $OPTIND - 1`

# Process the remaining command line args
for arg in "$@"; do
  case $arg in
    *=*) var=`echo $arg|awk -F\= '{printf "%s",$1}' -`
         val=`echo "$arg"|awk '{i=index($0,"=")+1;printf "%s",substr($0,i)}' -`
         # add this variable definition to the current environment
         [ -n "$var" ] && eval ${var}=\"\$val\" # preserve quoted assignments
         case $var in
              type) rtd_type="$val" ;;         # carbon or physical rtd
               ver) nemo_version="$val" ;;     # git version, tag or branch
              repo) nemo_source_repo="$val" ;; # location of git repository
              exec) nemo_rtd_exe="$val" ;;         # name for the executable created here
                 *) bail "Invalid command line arg --> $arg <--" ;;
         esac
         ;;
    *) bail "Invalid command line arg --> $arg <--" ;;
  esac
done

[ -z "$nemo_version" ] && usage -e "A version number/tag or branch is required on the command line."
if [ $build_nemo_rtd_exe -eq 1 ]; then
  # The name of the executable is not required unless it is to be built
  [ -z "$nemo_rtd_exe" ] &&
    usage -e "A name for the output executable is required on the command line ...exec=name"
fi

[ -z "$nemo_source_repo" ] && usage -e "The source repository name is missing."
[ ! -d "$nemo_source_repo" ] && usage -e "Repository is not a directory --> $nemo_source_repo <--"
# Ensure this is a full pathname
nemo_source_repo=$(cd $nemo_source_repo; pwd)


# This script is intended to be run on the back end
case $this_host in
  c1*|c2*) ;; # This is spica or hadar  ...OK
        *) bail "This should be run on a back end machine" ;;
esac

# Set up env to use git
GIT_PATH=/users/tor/acrn/rls/local/aix64/bin
[ ! -d "$GIT_PATH" ] && bail "$GIT_PATH is not a directory"
[ ! -s "$GIT_PATH/git" ] && bail "$GIT_PATH/git is missing"
[ ! -x "$GIT_PATH/git" ] && bail "You require execute permission for $GIT_PATH/git"
add2path $GIT_PATH

# Define netcdf details
# No longer used; now used nfconfig libs
#netcdf_include="/users/tor/acrn/rls/local/aix64/netcdf3.6.3/include";
#netcdf_lib="/users/tor/acrn/rls/local/aix64/netcdf3.6.3/lib";

# Create a temporary directory and change to it
CWD=`pwd`
tmpd=$CCRNTMP/tmp_build_nemo_${this_host}_$stamp
mkdir $tmpd || bail "Cannot create temporary dir $tmpd"

# Change to the tmp dir and build the executable
cd $tmpd

# path_to_rtd is the dir path (relative to the top git source dir) in which nemo code
# lives and is used by git archive to extract the nemo subset of the repository source
path_to_rtd=rtd

# cd $nemo_source_repo
git archive --remote=$nemo_source_repo --format=tar $nemo_version $path_to_rtd | \
  (cd $tmpd && tar xf -) ||
  bail "Unable to extract revision --> $nemo_version <-- from repository $nemo_source_repo"


# Make everything user writeable so that an overwrite will clobber existing files
chmod -R u+w $path_to_rtd
cd $path_to_rtd

if [ $build_nemo_rtd_exe -eq 1 ]; then
  if [ $type = 'carbon-canoe' ]; then
   input_f90='ccc_nemo_carbon-canoe_rtd.F90'
  elif [ $type = 'carbon-pisces' ]; then
   input_f90='ccc_nemo_carbon-pisces_rtd.F90'
  elif [ $type = 'carbon-cmoc' ]; then
   input_f90='ccc_nemo_carbon-cmoc_rtd.F90'
  elif [ $type = 'physical' ]; then
   input_f90='ccc_nemo_physical_rtd.F90'
  elif [ $type = 'ice' ]; then
   input_f90='ccc_nemo_ice_rtd.F90'
  else
    bail "type must be one of 'carbon-canoe', 'carbon-pisces', 'carbon-cmoc', 'physical' or 'ice'"
  fi

  # Build the nemo-rtd executable
#  xlf90 -O3 -qmaxmem=-1 -qdbg -qfullpath -qwarn64 -qstrict -qfloat=nans:rrm:norsqrt:nofold -qreport -qflttrap=ov:zero:inv:imp:enable -qsigtrap -qsuppress=1501-245 -qalias=intptr -qextname -qautodbl=dbl4 -qarch=pwr7 -qtune=pwr7 -qnocheck -qspillsize=3000 -qnoescape -qxflag=ngenstub -bmaxstack:0xF0000000 -qnoundef -qnosave -qtbtable=full -qxref -qattr -bnoquiet -qinitauto=7FF7FFFF -bnoquiet -o  nemo_rtd_exe  ${input_f90} uvic_netcdf.f -I ${netcdf_include}  -L ${netcdf_lib}  -lnetcdf $LINK

# Compile using new NetCDF libs
  xlf90_r -o nemo_rtd_exe ccc_nemo_rtd_utils.F90 ${input_f90} uvic_netcdf.f `nf-config --fflags --flibs`

  chmod g+rx nemo_rtd_exe  

  [ $? -ne 0 ] && bail "Problem building nemo-rtd executable"
  # Copy the executable to the tmp dir
  cp nemo_rtd_exe $tmpd/$nemo_rtd_exe
  cd $tmpd
  [ ! -s "$nemo_rtd_exe" ] && bail "Unable to create nemo-rtd executable $nemo_rtd_exe"
  # Save the nemo executable to RUNPATH/DATAPATH
  save $nemo_rtd_exe $nemo_rtd_exe || bail "Problem while saving $nemo_rtd_exe"
  release $nemo_rtd_exe
  echo "Saved $nemo_rtd_exe on RUNPATH $RUNPATH"
fi

cd $CWD
if [ $keep_tmpd -eq 1 ]; then
    echo "Temporary directory remains in $tmpd"
else
    rm -fr $tmpd
fi 


