#!/bin/bash
# helper utility to help setup cmorization using python

#=========
# Preamble
#=========
# Define working directory
WRKDIR_NAME="netcdfconv"
if [ -z "$1" ]; then
    # no arg given, create in CWD
    WRK_DIR="$WRKDIR_NAME"
else
    if [ ! -d $1 ]; then
        mkdir -p $1
    fi
    # create in directory given at CLI
    WRK_DIR="$1/$WRKDIR_NAME"
fi

# Add a "version" number if this directory already exists
DIRVER=01
WRK_DIR0=$WRK_DIR
while [ -d ${WRK_DIR} ]; do  
    WRK_DIR=${WRK_DIR0}${DIRVER}
    DIRVER=`echo $DIRVER | awk '{printf "%02d",$1+1}'`  
done

# set other useful environment variables
CWD=$(pwd)
SCRIPT_DIR=$(dirname $0)            # relative path to this script
SCRIPT_DIR=$(cd $SCRIPT_DIR && pwd) # absolute path to this script
datef=$(date +"%Y-%m-%d %T")        # date
case $(hostname) in                 # determine hall number
    hpcr1-* | *ppp1* | cs1be* ) HALLN=1 ;;
    hpcr2-* | *ppp2* | cs2be* ) HALLN=2 ;;
    hpcr3-* | *ppp3* | cs3be* ) HALLN=3 ;;
    hpcr4-* | *ppp4* | cs4be* ) HALLN=4 ;;
    * ) 
        echo "pycmor must be ran on an eccc ppp machine"
        exit 1 ;;
esac
cd $SCRIPT_DIR
NCCONV_HASH=$(git rev-parse HEAD)           # hash of ncconv
NCCONV_DIR=$(git rev-parse --show-toplevel) # absolute path of ncconv repo
cd $CWD

#=========================
# Setup Working Directory
#=========================
mkdir $WRK_DIR
cd $WRK_DIR

# bring in pertinent files
cp $NCCONV_DIR/pycmor/callcp.sh .
if [ $? -eq 1  ]; then echo 'Could not locate NCCONV_DIR. Exiting.'; exit; fi # if copying callcp.sh fails, abort
ln -s $NCCONV_DIR/cmor_tools/CMIP6_CVs/ .
ln -s $NCCONV_DIR/cmor_tools/cmip6-cmor-tables/ .
ln -s $NCCONV_DIR/tables/cccma_user_input.json .
# set version component of output file path
python $NCCONV_DIR/pycmor/set_dataset_version.py

# clone in experiment table (most up-to-date master branch) and store hash in variable
git clone git@gitlab.science.gc.ca:CanESM/cmip6_experiments.git --branch master --single-branch
EXPTAB_HASH=$(cd cmip6_experiments/ ; git rev-parse HEAD)

#===================
# Logging and Output
#===================
# Log hashes of both the current ncconv repo and any other external repos
cat > .config_pycmor.log <<EOF
config-pycmor
Date: ${datef}
-------------
ncconv            commit: $NCCONV_HASH
cmip6_experiments commit: $EXPTAB_HASH
EOF

# create script to set up env and output directions
cat > path_export.sh <<EOF
export PATH=$NCCONV_DIR/bin:$NCCONV_DIR/pycmor:\$PATH
export CMOR_WRK_DIR=$WRK_DIR
export NCCONV_DIR=$NCCONV_DIR
export HALLN=$HALLN
EOF

# print directions
echo "You should now:"
echo "  cd $WRK_DIR"
echo "  source path_export.sh"
echo "  source activate py2_cmor_v1"
echo "and then edit callcp.sh as needed and execute."
echo "For for further info, see the full documentation:"
echo "  http://hpfx.science.gc.ca/~scrd104/documentation/pycmor"
