#!/usr/bin/env bash

currentPerformanceYear=$(($1))
test_mode='false'
maxPerformanceYear=2027

Red='\033[0;31m'
Green='\033[0;32m'
bold=$(tput bold)

# checks the exit code of the last command and exits if not successful code 0.
function exitOnFailure () {
  if (( $? != 0 )); then
    echo -e "${Red}\n${bold}Update failed."
    exit
  fi
}

# checks for the -t (testmode) flag.
OPTIND=2
while getopts ":t" option; do
  case $option in
    t) 
      test_mode='true';;
    \?) 
      echo "Error: Invalid flag. Only -t or none allowed."
      exit;;
  esac
done


# This script is not made to work for years prior to 2022.
if (( $currentPerformanceYear >= 2022 )) && (( $currentPerformanceYear <= $maxPerformanceYear )); then

  echo -e "Compiling Typescript..."
  tsc -p .

  # Update the measures-data, if there are any updates:
  node dist/scripts/measures/$currentPerformanceYear/update-measures.js \
    $currentPerformanceYear $test_mode
  exitOnFailure

  if [ $test_mode == 'false' ]; then
    echo -e "Ingesting the Spec Urls, if those files exist..."
    node dist/scripts/measures/lib/ingest-specifications-links.js \
      $currentPerformanceYear
    exitOnFailure

    echo -e "Ingesting Quality and QCDR strata..."
    node dist/scripts/measures/$currentPerformanceYear/ingest-strata.js \
      $currentPerformanceYear \
      util/measures/$currentPerformanceYear/qcdr-strata.csv
    exitOnFailure

    node dist/scripts/measures/$currentPerformanceYear/ingest-strata.js \
      $currentPerformanceYear \
      util/measures/$currentPerformanceYear/quality-strata.csv
    exitOnFailure

    echo -e "Validating new measures-data.json..."
    node dist/scripts/validate-data.js measures $currentPerformanceYear measures/$currentPerformanceYear/measures-data.json
    exitOnFailure

    echo -e "Sorting measures by category and measureId..."
    node dist/scripts/measures/lib/sort-measures.js $currentPerformanceYear
    exitOnFailure

    echo -e "Ordering all measures' fields..."
    node dist/scripts/measures/lib/order-measure-fields.js $currentPerformanceYear
    exitOnFailure

    echo -e "Updating MVP files..."
    npm run build:mvp $currentPerformanceYear
    exitOnFailure
  fi
  
  echo -e "${Green}\n${bold}Update complete."
  exit

else
  echo -e "${Red}${bold}Performance year ${currentPerformanceYear} not valid."
fi
