#!/bin/sh
# script/cibuild: run the CI build. The Gitea workflow runs this on
# push, and it is the single entrypoint that covers everything:
#
#   1. the main Dockerfile, which runs the clean `hugo --minify`
#      production build (`make test`)
#   2. script/lint, which builds Dockerfile.lint's `lint` stage
#   3. script/fmt-check, which builds Dockerfile.lint's `fmt-check`
#      stage
#
# Steps 2 and 3 are delegated to the same scripts a developer runs, so
# CI cannot drift from `make check`. They are separate builds rather
# than a `RUN make check` inside the main image because script/lint is
# itself a `docker build`: shelling back into `make check` from an image
# would be docker-in-docker inside a bare alpine with no docker client
# and no daemon socket. See Dockerfile.lint for the full reasoning.
#
# The main image build below only implies a passing production build
# because of CHECK_EPOCH. Docker keys the `RUN make test` layer on
# content, so on an unchanged tree it is served from cache: the build
# never executes and the image build still exits 0. Passing a value that
# differs on every invocation invalidates that layer and everything
# below it, while the script/bootstrap toolchain layer above it keeps
# caching. script/lint and script/fmt-check each do the same for their
# own stage.
set -eu

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

main() {
    cd "$ROOT"
    # 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" .

    "$SCRIPT_DIR/lint"
    "$SCRIPT_DIR/fmt-check"
}

main "$@"
