#!/bin/sh
# Download the pinned tool versions (Linux amd64, static) and verify their
# SHA-256 before use. The result goes into the recovery bundle (charter §9).
#
#   tools/fetch-binaries DEST_DIR
#
# Hash provenance, recorded 2026-09-24:
#   restic   matches upstream SHA256SUMS of the release
#   age, gocryptfs: upstream publishes signatures/proofs, not a SHA256SUMS
#            file; hashes pinned on first download (trust on first use).
#            Verify against the upstream signatures when changing versions.
. "$(dirname "$0")/lib.sh"
need curl sha256sum tar bzip2
[ $# -eq 1 ] || die "usage: fetch-binaries DEST_DIR"
dest=$1; mkdir -p "$dest/bin" "$dest/downloads"

AGE_V=v1.3.2
AGE_URL=https://github.com/FiloSottile/age/releases/download/$AGE_V/age-$AGE_V-linux-amd64.tar.gz
AGE_SHA=cbe24006683f8eb669266162894b9a522a1af52f2665fbc63a4bb032ed26ac10
RESTIC_V=0.19.1
RESTIC_URL=https://github.com/restic/restic/releases/download/v$RESTIC_V/restic_${RESTIC_V}_linux_amd64.bz2
RESTIC_SHA=f415415624dcc452f2a02b8c33641791a8c6d6d3b65bbb3543fcf9a25151585c
GOCRYPTFS_V=v2.6.1
GOCRYPTFS_URL=https://github.com/rfjakob/gocryptfs/releases/download/$GOCRYPTFS_V/gocryptfs_${GOCRYPTFS_V}_linux-static_amd64.tar.gz
GOCRYPTFS_SHA=49b8c0eb0f6373b6ac99c394a52909d8478e74c08d0961527c1162967cc28c44

get() {  # URL SHA
    f=$dest/downloads/$(basename "$1")
    [ -f "$f" ] || curl -fsSL -o "$f" "$1" || die "download failed: $1"
    printf '%s  %s\n' "$2" "$f" | sha256sum -c --quiet - || { rm -f "$f"; die "CHECKSUM MISMATCH for $1 (file removed)"; }
    printf '%s' "$f"
}

f=$(get "$AGE_URL" "$AGE_SHA")
tar -xzf "$f" -C "$dest/bin" --strip-components=1 age/age age/age-keygen age/age-plugin-pq age/age-inspect
f=$(get "$RESTIC_URL" "$RESTIC_SHA")
bzip2 -dc "$f" > "$dest/bin/restic"
f=$(get "$GOCRYPTFS_URL" "$GOCRYPTFS_SHA")
tar -xzf "$f" -C "$dest/bin" gocryptfs gocryptfs-xray
chmod 755 "$dest/bin"/*

{
    printf 'Tool versions in this bundle (Linux amd64, static), fetched %s\n\n' "$(date +%F)"
    "$dest/bin/age" --version | sed 's/^/age /'
    "$dest/bin/restic" version
    "$dest/bin/gocryptfs" -version
    printf '\nSHA-256 of the downloaded release files:\n'
    (cd "$dest/downloads" && sha256sum *)
} > "$dest/VERSIONS.txt"
say "binaries in $dest/bin, versions in $dest/VERSIONS.txt"
