#!/bin/bash
set -e
# This script checks for any differences between the build's var_hashes.json 
# file and the stored one. If a difference is noted, it overwrites the stored
# file with the produced one, and commits/pushes to gitlab
#
# Note that since the pipelines will fail if frozen variables are altered, this 
# script will only update non-frozen hashes.

BLD_HASH_FILE=netcdfconv/var_hashes.json
STRD_HASH_FILE=$NB_SCRPT_DIR/var_hashes.json

# get most recent commit incase previous stages/jobs pushed updates
git checkout $NB_BRANCH ; git pull --ff-only        

# check for differences
diff $BLD_HASH_FILE $STRD_HASH_FILE >> /dev/null 2>&1 && differences=0 || differences=1
if [ "$differences" -eq "1" ]; then
    echo "Hash changes noted"
    echo "Updating stored versions..."

    updates=""

    # find out what var-table pairs were updated were updated
    echo "Updates in:"
    for f in $(find . -name 'hash_deltas.log'); do
        # extract table name and runid
        tmp=$(dirname $f)
        tmp2=$(dirname $tmp)
        CMORtable=$(basename $tmp)
        runid=$(basename $tmp2)

        # extract changed variables
        vars=$(cat $f)

        for v in $vars; do
            update_info=${v}-${CMORtable}-${runid}
            printf "\t${update_info}\n"
            updates=${updates}" "${update_info}
        done
    done

    # update file/commit/push
    cp -f $BLD_HASH_FILE $STRD_HASH_FILE
    git add $STRD_HASH_FILE
    git commit -m "Updated stored/unfrozen hashes for $updates"
    git push $NCCONV_REPO HEAD:$NB_BRANCH
else
    echo "No hash updates noted"
fi
