#!/bin/bash
#
#   Usage: clone-canesm [letter options] [defs]
#          Quantities in square brackets are optional
#
# Purpose: Extract code from the CanESM5 super repo on gitlab into a local directory
#
# Options:
# All options begin with a dash (-) and must appear before any other command line arg
# Single letter options may be combined, as in "clon-canesm -vv ..."
#
########################################################################
#
# Larry Solheim ...Sept 2017

FULLPATH=$(type $0|awk '{print $3}') # pathname of this script
Runame=$(basename $FULLPATH)
usage() {
  err_exit=0
  if [ "$1" = "-e" ]; then
    err_exit=1
    shift
  fi

  [ -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 a time stamp to be used in file names etc
stamp=$(date "+%j_%H%M%S"_$$)

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

# Set defaults

verbose=0

# A url pointing to the CanESM5 repo on gitlab
canesm_repo=git@gitlab.science.gc.ca:CanESM/CanESM5.git

# The commit to checkout after the repo has been cloned
canesm_ver=''

# A local sub directory that will contain the cloned repository
canesm_root=''

# process command line options
while getopts vxh opt
do
  case $opt in
    v) verbose=$((verbose + 1)) ;;
    x) set -x ;;
    h) usage ;;
    -) shift; break ;; # end of options
    ?) usage -e $USAGE ;;
  esac
done
shift $((OPTIND - 1))

# Process any 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
         val=`echo $val|sed 's/^ *//; s/ *$//'`  # remove leading and trailing space
         [ -z "$val" ] && usage -e "Invalid command line arg --> $arg <-- Empty value."
         case $var in
           canesm_repo) eval sbu_${var}=1 ;;
           canesm_root) eval sbu_${var}=1 ;;
           canesm_ver)  eval sbu_${var}=1 ;;
           *) usage -e "Invalid command line arg --> $arg <-- Unknown variable." ;;
         esac
         ;;
    *) if [ -z "$canesm_root" ]; then
         # The first non-definition arg should be the name of the
         # local directory that will contain the cloned repo
         # unless canesm_root was previously defined via canesm_root=val on the command line
         canesm_root=$arg
       elif [ -z "$canesm_ver" ]; then
         # The second (or first if canesm_root=val was on the command line) non-definition arg
         # should be the CanESM5 commit to checkout after cloning
         # unless canesm_ver was previously defined via canesm_ver=val on the command line
         canesm_ver=$arg
       else
         usage -e "Invalid command line arg --> $arg <--  canesm_root and canesm_ver are already defined."
       fi
       ;;
  esac
done

[ -z "$canesm_root" ] && { canesm_root=CanESM5; echo "canesm_root was not defined using canesm_root=$canesm_root"; }
[ -z "$canesm_ver" ]  && { canesm_ver=HEAD; echo " canesm_ver was not defined using canesm_ver=$canesm_ver"; }

echo "canesm_repo=$canesm_repo  canesm_ver=$canesm_ver  canesm_root=$canesm_root"

# Clone the CanESM5 super repo (this contains all source dirs as submodules)

git clone $canesm_repo $canesm_root || bail "Unable to clone $canesm_repo"

# Change to the cloned repo and checkout desired revision
cd $canesm_root
canesm_HEAD=$(git rev-parse HEAD)
echo "canesm_HEAD = $canesm_HEAD"
# Convert a commit named "HEAD" to the corresponding sha1 hash
[ x"$canesm_ver" = x"HEAD" ] && canesm_ver=$canesm_HEAD
git checkout $canesm_ver ||
    bail "Unable to check out revision $canesm_ver from $canesm_repo"
echo "clone-canesm: Checked out revision $canesm_ver from $canesm_repo"

# Update submodules
git submodule update --init --recursive || bail "Problem updating submodules"

# Define the full pathname of directories containing relevant source repos
AGCMSRC=$(readlink -f $canesm_root/CanAM)
DIAGSRC=$(readlink -f $canesm_root/CanDIAG)
CPLSRC=$(readlink -f $canesm_root/CanCPL)
NEMOSRC=$(readlink -f $canesm_root/CanNEMO)

sleep 5

[ -d $AGCMSRC ] || bail "$AGCMSRC is not a directory"
[ -d $DIAGSRC ] || bail "$DIAGSRC is not a directory"
[ -d $CPLSRC ]  || bail "$CPLSRC is not a directory"
[ -d $NEMOSRC ] || bail "$NEMOSRC is not a directory"

