#!/bin/bash
set -euo pipefail

readonly consensus_dir="$1"

all_queries() {
    find ./queries -type d -maxdepth 1 -mindepth 1 -print0 | xargs -0 -n1 basename | sort
}

has_consensus() {
    local query="$1"
    test -s "${consensus_dir}/${query}"
}

in_quotes() {
    echo -n '"'
    sed 's/\\/\\\\/g' | sed 's/"/\\"/g' | tr -d '\n'
    echo -n '"'
}

consensus() {
    local query="$1"
    local line

    while IFS= read -r line; do
        echo -n "    "
        cut -f1 <<< "$line" | tr -d '\n'
        echo -n ": "
        cut -f2 <<< "$line"
    done <<< "$(grep consensus < "${consensus_dir}/${query}")"
}

query_entry() {
    local query="$1"

    echo "  - id: ${query}"
    echo "    selector: $(in_quotes < "./queries/${query}/selector")"
    echo -n "    document: "
    ./src/oneliner_json.py < "./queries/${query}/document.json"

    if [[ -f "./queries/${query}/ALLOW_UNORDERED" ]]; then
        echo "    ordered: false"
    fi


    if has_consensus "$query"; then
        consensus "$query"
    fi
}

main() {
    local query

    cat <<EOF
# This file was generated by src/compile_regression_suite.sh from
# https://github.com/cburgmer/json-path-comparison/
# You probably don't want to change this manually.

# This file contains all queries implemented by the comparison and holds all
# consensus results where such a consensus exist.
# It can be used to track regressions in implementations. This file can be
# complemented with the report specifically generated for each implementation.

# If a query can possibly return only one element, the consensus calls out both
# possible response types found in implementations: an array with one element
# and just the element ("scalar-consensus").
# If a query has no match, the consensus calls out the specific NOT_FOUND
# response as returned by some implementations ("not-found-consensus"). If this
# coincides with a query that could possibly only return one match, it also
# calls out that possible answer ("scalar-not-found-consensus").
# In all cases you should pick the response type that matches your
# implementation.
#
# The consensus is not always a valid JSON document. In the case that the
# consensus is that a query is not supported it will contain the string
# "NOT_SUPPORTED".

EOF

    echo "queries:"
    while IFS= read -r query; do
        query_entry "$query"
    done <<< "$(all_queries)"
}

main
