#/bin/bash

# INTRODUCTION
# This script links ESP-r with Calibro and performs the following functions:
# 1. upload zipped Calibro input files (tarball file is command line argument) to cloud
# 2. add model to Calibro workspace invoking Calibro RESTful API, this is a two part process
#    a) download the zipped file from cloud (uploaded in part 1. above) to Calibro UI server
#    b) add the model to Calibro DB under models owned by this user
# 3. run this calibration using Calibro
# Tasks 2 and 3 require python3 scripts which are bundled as part of Calibro RESTful API
# This script requires the Calibro input files to be named according to Calibro requirements. 
# The files are then zipped (*.tar.gz) and the filename is supplied to this script as command line argument
# Invocation is done by the command calibrateme.bash calibro_input_file_name.tar.gz
# Upon completion of calibration the resulting json file is available in the folder this script is run from

# EXAMPLE USAGE
# /usr/opt/bin/ESP-r/bin/calibrateme.bash ~/ESP-r_models/ModelName/cfg/calibro_files.tar.gz


# Get directory this script is in (which should also be location of python3 RESTful API files)
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

errorcode=0

# get MD5 sum of $1
md5=`md5sum $1`
md5="${md5% *}" # remove filename from string
md5=`echo $md5 | xargs` # remove whitespace

# get basename of file given as $1
extension="${1##*.}"
filename="${1%.*}"          # remove .gz
filename="${filename%.*}"   # remove .tar
filename="${filename##*/}"  # remove path
#echo "file name is $filename"

# upload $1 to cloud
curl --silent -F "file=@$1" https://file.io > tmpfile

# get link to this file if upload was successful
runOK=`more tmpfile | jq '.success'`
link=`more tmpfile | jq '.link'`
link=`echo $link | tr -d '"'` # remove quotes

if [ $runOK == "true" ]; then
  echo "Calibration files uploaded to cloud"

  ################
  #### GET ID ####
  ################
  GetID="$DIR/GetID.py"
  python3 $GetID "$DIR/"
  #python3 GetID.py # may be used if both scripts and input files are in the same directory
  model_list=`more model_list.json`
  if [ "$model_list" != "{\"posts\":[]}" ]; then
    maxid=`more model_list.json | jq '.posts[-1].id'` # get last Calibro model id for this user
    maxid=`echo $maxid | tr -d '"'` # remove quotes
    if [ $maxid -lt 0 ]; then
      errorcode=$maxid
      break
    fi
  else
    maxid=0
  fi

  # add this model to this users Calibro models, 
  # i.e. download this file from cloud location (uploaded to a few lines back) to server
  # and add the file name and path to DB
  sed "s,.*mname.*,mname = '$filename'," -i  "$DIR/variables.py"
  sed "s,.*FNP.*,FNP = '$link'," -i  "$DIR/variables.py"

  ###################
  #### ADD MODEL ####
  ###################
  AddModel="$DIR/AddModel.py"
  python3 $AddModel "$DIR/"
  #python3 AddModel.py # may be used if both scripts and input files are in the same directory

  echo "Calibration model called $filename added to your Calibro models"

  # check if this model has been uploaded to server
  i=0
  while : ; do
    sleep 20;

    ################
    #### GET ID ####
    ################
    GetMD5="$DIR/GetMD5.py"
    python3 $GetMD5 "$DIR/" # get id and MD5 of this model (called newid) and download it
    #python3 GetMD5.py # get id and MD5 of this model (called newid) may be used if both scripts and input files are in the same directory
    if [ ! -f model_MD5.json ]; then
      echo "Error: MD5 json file does not exist"
      exit
    fi
    newid=`more model_MD5.json | jq '.posts[-1].id'`
    newid=`echo $newid | tr -d '"'` # remove quotes

    if [ $newid -gt $maxid ]; then
      uploadedMD5=`more model_MD5.json | jq '.posts[-1].md5'`
      uploadedMD5=`echo $uploadedMD5 | tr -d '"'` # remove quotes

      # if MD5 of file uploaded to cloud and of file downloaded to server match then run calibration
      if [ "$md5" = "$uploadedMD5" ]; then
        sed "s,.*pid.*,pid = '$newid'," -i  "$DIR/variables.py"
        echo "Calibration started"

        #########################
        #### RUN CALIBRATION ####
        #########################
        Run="$DIR/Run.py"
        python3 $Run "$DIR/" 
        #python3 Run.py # may be used if both scripts and input files are in the same directory
        break
      else
        echo "ERROR: MD5 mismatch between file uploaded to cloud and downloaded to server"
        echo "md5 is >>>$md5<<<"
        echo "new is >>>$uploadedMD5<<<"
      fi
    fi  

    let "i++"
    if [ $i -gt 100000 ]; then
      echo "ERROR: calibrateme while loop overran maximum allowed iterations"
      break
    fi
  done # end while loop
else
  errorcode=-3
fi

# Error reporting
if [ $errorcode -eq -1 ]; then
  echo "ERROR: model_list.json file does not exist"
elif [ $errorcode -eq -2 ]; then
  echo "ERROR: model id exceeded maximum allowable limit check your model_list.json file"
elif [ $errorcode -eq -3 ]; then
  echo "ERROR: curl did not upload file"
fi

# Cleanup
rm -fr tmpfile model_MD5.json model_list.json
exit



















