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

# Set name of working dir
dirver=01

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

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

# set useful environment variables
CWD=$(pwd)           
NCCONV_DIR=$CWD                     # ncconv repo dir
NCCONV_HASH=$(git rev-parse HEAD)   # hash of ncconv
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

# create working directory
mkdir $WRK_DIR
cd $WRK_DIR

# bring in pertinent files
cp $NCCONV_DIR/CI/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 .

# 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)

# 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 "and then edit callcp.sh as needed and execute."
