#!/bin/sh
# script/cibuild: run the CI build. The Gitea workflow runs this on
# push, and it is the single entrypoint that covers everything. Two
# container builds, in order:
#
#   1. script/lint, which builds Dockerfile.lint -- the lint runs as a
#      build step there
#   2. the main Dockerfile, which runs the non-lint checks: the clean
#      `hugo --minify` production build (script/test) and the read-only
#      prettier check (script/fmt-check)
#
# Lint goes first, for fail-fast feedback: on a runner with no cached
# script/bootstrap layer the main image compiles Hugo from source, and a
# lint failure should not wait behind that. It is a separate build
# rather than a step inside the main image because script/lint is itself
# a `docker build`, and a docker build cannot run a docker build. See
# Dockerfile.lint for the full reasoning.
#
# The lint is delegated to the same script a developer runs, so CI
# cannot drift from `make check`.
#
# Neither build implies a passing check without CHECK_EPOCH. Docker keys
# the check layers on content, so on an unchanged tree they are served
# from cache: nothing executes and the build still exits 0. Passing a
# value that differs on every invocation invalidates those layers and
# everything below them, while the script/bootstrap toolchain layer
# above keeps caching. script/lint does the same for its own build.
set -eu

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

main() {
    cd "$ROOT"
    "$SCRIPT_DIR/lint"

    # Assigned to a variable rather than substituted inline in the
    # argument list: a command substitution that fails inside an
    # argument does not trip `set -e`, so the inline form would quietly
    # pass an empty string and restore the cached false green. As the
    # whole of an assignment its exit status is the command's, so
    # `set -e` catches it. `%N` keeps two invocations within the same
    # second distinct; busybox date silently drops `%N` and still exits
    # 0, so `$$` is appended to cover that degradation.
    epoch="$(date +%s%N)$$"
    docker build --build-arg CHECK_EPOCH="$epoch" .
}

main "$@"
