#!/usr/bin/env bash

# Usage: env [ CC=... ] [ C_STANDARD=...] [ CXX=... ] [CXX_STANDARD=...] \
#            [ AR=... ] [ RANLIB=... ] [ STRIP=... ] [ DEBUG=... ] \
#            [ LTO=... ] ./build-id [ID_SALT]...
#
# Prints to stdout a SHA256 hash representing the current toolset, used by
# depends/Makefile as a build id for caching purposes (detecting when the
# toolset has changed and the cache needs to be invalidated).
#
# If the DEBUG environment variable is non-empty and the system has `tee`
# available in its $PATH, the pre-image to the SHA256 hash will be printed to
# stderr. This is to help developers debug caching issues in depends.

# This script explicitly does not `set -e` because id determination is mostly
# opportunistic: it is fine that things fail, as long as they fail consistently.

# Command variables (CC/CXX/AR) which can be blank are invoked with `bash -c`,
# because the "command not found" error message printed by shells often include
# the line number, like so:
#
#     ./depends/gen_id: line 43: --version: command not found
#
# By invoking with `bash -c`, we ensure that the line number is always 1

(
    # Redirect stderr to stdout
    exec 2>&1

    echo "BEGIN ALL"

    # Include any ID salts supplied via command line
    echo "BEGIN ID SALT"
    echo "$@"
    echo "END ID SALT"

    echo "BEGIN /gnu/store"
    bash -c "ls -1 /gnu/store | sort"
    echo "END /gnu/store"

    # LINES=\|COLUMNS=\|\|HOSTTYPE=\|OSTYPE=\|MACHTYPE=\|HOSTNAME=
    echo "BEGIN environment"
    bash -c "printenv | sort | grep -v '^\(BASE_CACHE=\|DISTNAME=\|DISTSRC=\|OUTDIR=\|SOURCES_PATH=\|JOBS=\|OPTIONS=\)'"
    echo "END environment"

    echo "END ALL"
) | if [ -n "$DEBUG_GENID" ] && command -v tee > /dev/null 2>&1; then
        # When debugging and `tee` is available, output the preimage to stderr
        # in addition to passing through stdin to stdout
        tee >(cat 1>&2)
    else
        # Otherwise, passthrough stdin to stdout
        cat
    fi | ${SHA256SUM} - | cut -d' ' -f1