#!/bin/bash

cd "$(dirname "$0")/.."

function checkout_at() {
  repo=$1; url=$2; sha=$3
  if [ ! -d "$repo" ]; then
    git clone "https://github.com/$url" "$repo"
  fi

  pushd "$repo"
  git fetch && git reset --hard "$sha"
  popd
}

# Define list of arguments expected in the input
optstring="s"

while getopts ${optstring} arg; do
  case ${arg} in
    s)
      SKIP_DOWNLOAD='true'
      echo "Skip download"
      ;;
    ?)
      echo "Invalid option: -${OPTARG}."
      ;;
  esac
done

if [[ $SKIP_DOWNLOAD != 'true' ]]; then
    #  checkout_at "examples/<name>" "<git name>/<git project>" "<commit id>"
    echo "TODO: Download examples"
fi

skipped_files=()
examples_to_parse=()
all_examples=$(find examples -name '*.gren')
known_failures=$(cat script/known-failures.txt)
for example in $all_examples; do
  if [[ ! $known_failures == *$example* ]]; then
    examples_to_parse+=($example)
  else
    skipped_files+=($example)
  fi
done

start=`date +%s.%N`
tree_sitter_report=$(echo ${examples_to_parse[@]} | xargs -n 100000 npx tree-sitter parse --quiet --stat)
end=`date +%s.%N`

ret_code=$?

echo -e "-----------------------------------------------------------------\n$tree_sitter_report \n -----------------------------------------------------------------\n"

skipped=$( echo ${#skipped_files[@]} )
# This doesn't work on macos due to how date is used and will default to empty
runtime=$( echo "$end - $start" | bc -l )

printf "Skipped: %d \nTook: %s\n" $skipped $runtime

exit $ret_code
