#!/usr/bin/env bash
set -euo pipefail

repository=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
temporary=$(mktemp -d)
trap 'rm -rf "$temporary"' EXIT

for copy in a b; do
    mkdir -p "$temporary/$copy/source"
    tar \
        --exclude=.git \
        --exclude=.worktrees \
        --exclude=dist \
        --exclude=target \
        -C "$repository" -cf - . \
        | tar -C "$temporary/$copy/source" -xf -
    (
        cd "$temporary/$copy/source"
        CARGO_TARGET_DIR="$temporary/$copy/target" \
        SOURCE_DATE_EPOCH=0 \
        ./scripts/build-native-broker "$temporary/$copy/dist"
    )
done

artifact=agcoord-broker-x86_64-unknown-linux-musl
if ! cmp -s "$temporary/a/dist/$artifact" "$temporary/b/dist/$artifact"; then
    printf 'native broker rebuilds were not byte-for-byte identical\n' >&2
    sha256sum "$temporary/a/dist/$artifact" "$temporary/b/dist/$artifact" >&2
    exit 1
fi
# Two builds on one host share its Cargo home, so byte identity alone cannot show that the
# artifact is independent of the builder; refuse any embedded builder path (#249).
cargo_home=${CARGO_HOME:-"$HOME/.cargo"}
for builder_path in \
    "$(CDPATH= cd -- "$cargo_home" && pwd)" \
    "$(CDPATH= cd -- "$cargo_home" && pwd -P)" \
    "$repository" \
    "$temporary"; do
    if grep -aqF -- "$builder_path" "$temporary/a/dist/$artifact"; then
        printf 'native broker embeds a builder-specific path: %s\n' "$builder_path" >&2
        exit 1
    fi
done
# Two builds on one runner also share its C toolchain, so the digest is only pinnable when that
# toolchain is the declared one (#250).
if ! "$repository/scripts/native-toolchain" check "$temporary/a/dist/$artifact.provenance.json"; then
    printf 'refusing to report a reproducible digest built with an undeclared C toolchain\n' >&2
    exit 1
fi

"$repository/scripts/audit-native-broker" "$temporary/a/dist/$artifact"
printf 'reproducible native artifact: '
sha256sum "$temporary/a/dist/$artifact" | awk '{print $1}'
