#!/usr/bin/env bash
set -uo pipefail

cd "$(dirname "$0")/.." || exit 1

filter='.'
if [[ $# -gt 0 ]]; then
    files_json=$(printf '%s\n' "$@" | jq -R -s 'split("\n")[:-1]')
    read -r -d "" filter <<'jq'
def selected($path; $rel):
    any($files[]; . as $target
        | ($target | sub("/+$"; "") | sub("^\\./"; "")) as $clean
        | (if $clean | startswith("/") then $clean else $cwd + "/" + $clean end) as $abs
        | $path == $clean
            or $rel == $clean
            or $path == $abs
            or ($rel | startswith($clean + "/"))
            or ($path | startswith($abs + "/"))
    );
map(
    .file as $f
    | ($f | sub("^" + $cwd + "/"; "")) as $rel
    | select(selected($f; $rel))
)
jq
fi

json=$(emmylua_check --warnings-as-errors --output-format=json . 2> >(grep -v '^Check finished$' >&2))
check_status=$?
if ! jq -e type >/dev/null <<<"$json"; then
    if [[ $check_status -ne 0 ]]; then
        exit "$check_status"
    fi
    exit 1
fi
if ! filtered=$(jq --arg cwd "$PWD" --argjson files "${files_json:-[]}" "$filter" <<<"$json"); then
    exit 1
fi

jq -r '
        .[]
        | .file as $f
        | .diagnostics[]
        | "\($f):\(.range.start.line + 1):\(.range.start.character + 1)"
          + ": \(["error","warning","info","hint"][.severity-1])"
          + ": \(.message | rtrimstr(" ")) [\(.code)]"
    ' <<<"$filtered" \
    | sed "s|^$PWD/||"

if [[ $# -gt 0 ]]; then
    if jq -e 'any(.[]?.diagnostics[]?; .severity <= 2)' >/dev/null <<<"$filtered"; then
        exit 1
    fi
    exit 0
fi

exit "$check_status"
