#!/bin/sh
# script/docker: build the Docker image tagged with the project name.
# Identical in all repos; the tag comes from script/projectname.
# Generic: needs no adaptation.
#
# This builds the PRODUCT image only, and the product Dockerfile has no
# lint stage: linting lives in Dockerfile.lint and is run by
# script/lint. So a green here means `make fmt-check` and `make test`
# passed and the image built -- it says nothing about lint. The gates
# are script/check (which runs script/lint) and script/cibuild (which
# builds both files).
set -eu

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

main() {
    cd "$ROOT"
    # Same CHECK_EPOCH contract as script/cibuild, for the same reason
    # and with the same bare-assignment and `$$` requirements -- see the
    # comments there. This script is not the CI gate, but a local build
    # is almost always warm, so without this it would report a green the
    # tree had not earned and the two entrypoints would disagree about
    # whether the tree is clean. The Dockerfile now refuses to build
    # without a non-empty value, so this is required, not optional.
    epoch="$(date +%s%N)$$"

    # Version, commit and build date are computed here on the host,
    # where .git exists, and passed into the build. The build context
    # excludes .git (see .dockerignore), so the container cannot derive
    # them itself -- it used to try and always got "unknown", giving
    # every image a "commit: unknown" it could not be traced from.
    # VERSION comes from script/version, the source of truth shared with
    # the Makefile, so a Docker build reports the same string (tag,
    # dev-<sha>, or a -dirty variant) that a local build of the same
    # tree would.
    version="$("$SCRIPT_DIR/version")"
    commit="$(git rev-parse HEAD 2>/dev/null || echo unknown)"
    commit_date="$(git show -s --format=%cs HEAD 2>/dev/null || echo unknown)"

    docker build --build-arg CHECK_EPOCH="$epoch" \
        --build-arg VERSION="$version" \
        --build-arg COMMIT="$commit" \
        --build-arg COMMIT_DATE="$commit_date" \
        -t "$("$SCRIPT_DIR/projectname")" .
}

main "$@"
