#!/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
}

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}" "$@"
