#! /usr/bin/env bash
set +x

# This script iterates through each spec file and tries to run it with interpreter.
#
# USAGE:
#
# For std spec:
# $ spec/generate_interpreter_spec.sh std spec/interpreter_std_spec.cr

export SPEC_SUITE=$1
export OUT_FILE=$2
export CRYSTAL_BIN=${CRYSTAL_BIN:-./bin/crystal}
job_size=${3:-64}

command="$0 $*"
echo "# $(date --rfc-3339 seconds) This file is autogenerated by \`${command% }\`" > $OUT_FILE

run_spec () {
  spec=$1
  require="require \"./${spec##spec/}\""
  timeout 150 $CRYSTAL_BIN i $spec > /dev/null; exit=$?

  if [ $exit -eq 0 ] ; then
    echo "$require" >> $OUT_FILE
  else
    echo "# $require (failed to run)" >> $OUT_FILE
  fi
}

export SHELL=$(type -p bash)
export -f run_spec

find "spec/$SPEC_SUITE" -type f -iname "*_spec.cr" | LC_ALL=C sort | parallel -j $job_size run_spec {} 

cat $OUT_FILE | sort | sponge $OUT_FILE
