#!/bin/sh
set -e

# Registers the archives in `artifacts/` with radicle-artifact, in the release
# of the tag `releases/httpd/<version>`, with their files.radicle.dev URLs and
# checksums. Run it after `upload`. Running it again changes nothing.

outdir="$(dirname "$0")/artifacts"
version="$("$(dirname "$0")/version")"
tag="releases/httpd/$version"

for tool in rad rad-artifact jq sha256sum; do
  if ! command -v "$tool" >/dev/null; then
    echo "fatal: $tool is not installed" >&2
    exit 1
  fi
done

rad auth

artifact() {
  rad-artifact --no-announce --no-input "$@"
}

for target in $(cat "$(dirname "$0")/TARGETS"); do
  for bin in radicle-httpd radicle-search; do
    filename="$bin-$version-$target.tar.xz"
    filepath="$outdir/$filename"

    if [ ! -f "$filepath" ]; then
      echo "fatal: $filepath is missing" >&2
      exit 1
    fi
    (cd "$outdir" && sha256sum --check --quiet "$filename.sha256")
    sha256="$(cut -d' ' -f1 "$filepath.sha256")"

    echo "Registering $filename.."
    cid="$(artifact register "$filepath" --revision "$tag" -n "$filename" --json | jq -r .cid)"
    artifact location add --revision "$tag" --cid "$cid" \
      "https://files.radicle.dev/releases/$bin/$version/$filename"
    artifact metadata set --revision "$tag" --cid "$cid" sha256 "$sha256"
    if [ -f "$outdir/build-url" ]; then
      artifact metadata set --revision "$tag" --cid "$cid" ci-build "$(cat "$outdir/build-url")"
    fi
  done
done

rad sync --announce
echo "Registration successful."
