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

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
CORE_BIN="${JEANNIE_CORE_BIN:-${REPO_ROOT}/.lab/bin/jeannie-core}"

core_sources_newer() {
    local source

    while IFS= read -r source; do
        if [[ "${source}" -nt "${CORE_BIN}" ]]; then
            return 0
        fi
    done < <(find "${REPO_ROOT}/cmd/jeannie-core" -name '*.go' -type f)
    return 1
}

usage() {
    cat <<'EOF'
Usage: report-render [--title TITLE] [--details] [--only failures|warnings|problems|all] [--json]

Reads TSV rows from stdin:
  status<TAB>area<TAB>check<TAB>summary<TAB>detail<TAB>fix<TAB>graph<TAB>query

Statuses: ok, warn, fail, skip
EOF
}

if (($# > 0)); then
    case "$1" in
        -h | --help)
            usage
            exit 0
            ;;
    esac
fi

if [[ ! -x "${CORE_BIN}" || "${REPO_ROOT}/go.mod" -nt "${CORE_BIN}" ]] || core_sources_newer; then
    if ! command -v go >/dev/null 2>&1; then
        echo "go is required to build ${CORE_BIN}; run ./jeannie up or install golang-go." >&2
        exit 1
    fi
    mkdir -p "$(dirname "${CORE_BIN}")"
    GOCACHE="${GOCACHE:-${REPO_ROOT}/.lab/go-build-cache}" go build -o "${CORE_BIN}" "${REPO_ROOT}/cmd/jeannie-core"
fi

exec "${CORE_BIN}" report-render "$@"
