#!/bin/sh
# script/cibuild: run the CI build. Two container builds, in order:
# script/lint (Dockerfile.lint) and then the main image, which runs the
# non-lint checks. Both only prove anything because each passes its own
# fresh CHECK_EPOCH nonce: without it Docker serves the check layers
# from cache on an unchanged tree and the build exits 0 without running
# anything.
set -eu

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)"

main() {
    cd "$ROOT"
    # Lint first, for fail-fast feedback: it is its own container build
    # and computes its own CHECK_EPOCH. It runs here rather than inside
    # the main image because a docker build cannot run a docker build.
    "$SCRIPT_DIR/lint"
    # Assign on its own line: a failing command substitution inside an
    # argument does not trip `set -e`, which would silently degrade the
    # nonce to an empty constant. `$$` is required because busybox `date`
    # drops %N without erroring.
    epoch="$(date +%s%N)$$"
    # VERSION must be computed here, on the host: .dockerignore excludes
    # .git, so `git describe` cannot run in any build stage and fails
    # quietly there rather than erroring. Same own-line discipline as the
    # epoch. `|| true` keeps a failing describe from tripping `set -e`
    # and leaves the value empty; the guard below is then the single
    # place the fallback is applied, and it does fire — on an export with
    # no .git, or a repo with no commits yet. `unknown` is visibly wrong
    # in a binary in a way that an empty version is not.
    version="$(git describe --tags --always --dirty 2>/dev/null || true)"
    [ -n "$version" ] || version="unknown"
    docker build \
        --build-arg CHECK_EPOCH="$epoch" \
        --build-arg VERSION="$version" \
        .
}

main "$@"
