#!/bin/bash

set -e

function fixture() {
  url=$1
  sha=$2
  name=$(basename $url)
  path=examples/$name

  echo $name $path

  if [ ! -d $path ]; then
    git clone --depth=1 $url $path
  fi

  (
    cd $path
    git fetch origin $sha
    git reset --hard $sha
  )
}

fixture https://github.com/FluxML/Flux.jl f3c9ab71bc4ec19bc95f0cd67ac63616254b65a3
fixture https://github.com/pluskid/Mocha.jl 5e15b882d7dd615b0c5159bb6fde2cc040b2d8ee
fixture https://github.com/JuliaLang/IJulia.jl ad459e8d46a908c6b923cafa79572a610e2869bb
fixture https://github.com/GiovineItalia/Gadfly.jl f759d9c76b2a983eff314e307825cbcc7e2e5055

all_examples=$(find "examples" -type f -name '*.jl')
known_failures=$(cat script/known-failures.txt)
examples_to_parse=$(
  for example in $all_examples; do
    if [[ ! $known_failures == *$example* ]]; then
      echo $example
    fi
  done
)

echo $examples_to_parse | xargs -n 5000 tree-sitter parse -q -t

skipped=$( echo $known_failures | wc -w )
parsed=$( echo $examples_to_parse | wc -w )
total=$(( parsed + skipped ))
percent=$( bc -l <<< "100*$parsed/$total" )

printf "Successfully parsed %d of %d files (%.2f%%)\n" $parsed $total $percent
