#!/bin/bash

# TODO: move this into the client

set -uo pipefail

test_directory="parse_tests"

function usage() {
cat <<EOF >&2
Usage:

  $(basename "$0") [-h] [-a] -- Run parser golden tests in $test_directory

  where:
    -h  show this help text
    -a  accept new results (override test files)
EOF
exit 1
}

accept=false
while getopts ':ha' option; do
    case "$option" in
        h) usage
           ;;
        a) accept=true
           ;;
        :) printf "missing argument for -%s\n" "$OPTARG" >&2
           usage
           ;;
       \?) printf "illegal option: -%s\n" "$OPTARG" >&2
           usage
           ;;
    esac
done
shift $((OPTIND - 1))

test_files=$(find "$test_directory" -type f | grep "\.test$")

failed_tests=0
for test in ${test_files[@]}; do
    test_name="${test%.*}"
    expected="$test_name.expected"

    result=$(mktemp)
    node build/main.js parse $(cat "$test") > "$result" 2>&1
    if [ $accept = true ]; then
        echo "Updating $test_name"
        cat "$result" > "$expected"
        continue
    fi

    if [ ! -f "$expected" ]; then
        echo "Missing '$expected' (re-run with -a flag to create)"
        failed_tests=$(($failed_tests + 1))
    else
        echo "Testing $test_name"
        git --no-pager diff --no-index "$expected" "$result"
        failed_tests=$(($failed_tests + $?))
    fi
done

if [ ! $failed_tests = 0 ]; then
    echo "$failed_tests failed test(s)"
    exit 1
else
    echo "All tests passed"
fi
