#!/bin/bash
# Download all topology binaries into explicit disposable paths with vendor hashes.
fail() { printf 'ERROR: %s\n' "$*" >&2; exit 1; }
[[ $# == 3 ]] || fail 'Usage: download_binaries.sh RELEASE ABSOLUTE_BINARY_DIR ABSOLUTE_RESULTS_DIR'
RELEASE=$1
DEST=$2
RESULTS=$3
[[ "$RELEASE" =~ ^r[0-9]{2}\.[0-9]+$ && "$DEST" == /* && "$RESULTS" == /* ]] || fail 'Invalid release or output paths.'
case "$(uname -m)" in aarch64) PLATFORM=linux26aarch64;; x86_64) PLATFORM=linux26x86_64;; *) fail 'Unsupported architecture.';; esac
mkdir -p "$DEST" "$RESULTS" || exit 1
BASE="https://ftp.perforce.com/perforce/$RELEASE/bin.$PLATFORM"
curl --connect-timeout 20 --max-time 300 --retry 2 --retry-delay 1 -fsSL "$BASE/SHA256SUMS" -o "$DEST/SHA256SUMS" || fail 'Cannot download vendor checksum manifest.'
: > "$RESULTS/binary-sources.txt" || exit 1
for binary in p4 p4d p4broker p4p; do
   curl --connect-timeout 20 --max-time 300 --retry 2 --retry-delay 1 -fsSL "$BASE/$binary" -o "$DEST/$binary.partial" || fail "Cannot download $binary."
   hash=$(awk -v name="$binary" '$2 == "*" name || $2 == name {print $1}' "$DEST/SHA256SUMS")
   [[ "$hash" =~ ^[a-fA-F0-9]{64}$ ]] || fail "Missing/ambiguous checksum for $binary."
   printf '%s  %s\n' "$hash" "$DEST/$binary.partial" | sha256sum -c - || fail "$binary checksum mismatch."
   mv "$DEST/$binary.partial" "$DEST/$binary" || exit 1
   chmod 755 "$DEST/$binary" || exit 1
   "$DEST/$binary" -V > "$RESULTS/$binary-version.txt" 2>&1 || exit 1
   printf '%s/%s %s\n' "$BASE" "$binary" "$hash" >> "$RESULTS/binary-sources.txt" || exit 1
 done
