#!/bin/sh
set -e

# Builds the explorer bundle from the checked out tag `releases/httpd/<version>`
# with config/default.json, registers it as the collection `radicle-explorer` in
# the release of the tag and seeds it from the local artifact node. Run it after
# `register`. Running it again changes nothing.

explorer="$(cd "$(dirname "$0")/../../.." && pwd)"
version="$("$(dirname "$0")/version")"
tag="releases/httpd/$version"

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

# node-config also loads untracked files such as config/local.json.
if [ -n "$(git -C "$explorer" ls-files --others config)" ]; then
  echo "fatal: $explorer/config has untracked files, remove them" >&2
  exit 1
fi

rad auth

echo "Building the explorer bundle.."
(
  cd "$explorer"
  unset NODE_CONFIG NODE_CONFIG_ENV NODE_CONFIG_DIR VITE_RUNTIME_CONFIG
  npm ci --no-audit --no-fund
  npm run build
)

if ! rad-artifact node status >/dev/null 2>&1; then
  rad-artifact node start
fi

echo "Registering the explorer bundle.."
rad-artifact --no-announce --no-input register "$explorer/build" --collection \
  -n radicle-explorer --revision "$tag" --seed >/dev/null

rad sync --announce
echo "Registration successful."
