#!/usr/bin/env bash
# archie-update-check -- update discovery adapter for archied's /update command.
#
# Writes a releaseupdate.Snapshot JSON document to stdout. archied runs this
# via CommandCatalog (internal/releaseupdate/command.go), which never invokes
# a shell, so this file must be directly executable.
#
# "Installed" is the release the running binary was ACTUALLY built from,
# read via `archied -version` rather than trusted from git or filesystem
# state -- if a prior build/install step silently failed partway, the
# checkout can disagree with what's really running, and -version is the one
# source that cannot be wrong about that. The build stamp carries a
# git-describe suffix when HEAD has moved past the tag (1.7.0-4-g0736708);
# that suffix is stripped for the comparison, because unreleased commits are
# not an available update and would otherwise report one forever.
#
# "Available" is the newest release tag on the origin remote, via
# ls-remote -- no local fetch or working-tree state required, so this
# script has no side effects and no dependency on the checkout being
# buildable.
#
# Component IDs are "daemon" and "agent" -- the same convention
# releaseupdate.ComponentDaemon/ComponentAgent, archie-update-watchdog's
# report, and Service.Enrich (installtype.Type(), an observed archie-agent
# version) all expect. A check command using different IDs still works for
# the raw Installed/Available display, just without that enrichment or
# Report.Verify recognising it after an install.
set -euo pipefail

REPO="${ARCHIE_REPO_DIR:-$HOME/projects/archie-core}"
BIN="${ARCHIE_BIN:-$HOME/.local/bin/archied}"

# base 1.7.0-4-g0736708 -> 1.7.0
base() { printf '%s\n' "${1%%-*}"; }

installed_for() {
  "$BIN" -version 2>/dev/null | awk -v n="$1" '$1 == n { print $2; exit }'
}

latest_tag() {
  git -C "$REPO" ls-remote --tags --refs origin "$1/v*" 2>/dev/null |
    sed 's|.*refs/tags/||' | sed "s|^$1/v||" |
    sort -V | tail -1
}

daemon_installed="$(base "$(installed_for archied || true)")"
agent_installed="$(base "$(installed_for archie-agent || true)")"
daemon_available="$(latest_tag archied || true)"
agent_available="$(latest_tag archie || true)"

# An unreachable remote must not look like "up to date": leaving Available
# empty makes Snapshot.Available() skip the component rather than claim
# parity it never verified.
esc() { printf '%s' "${1:-}" | sed 's/\\/\\\\/g; s/"/\\"/g'; }

cat <<EOF
{
  "Components": [
    {
      "ID": "daemon",
      "Label": "Gateway",
      "Installed": "$(esc "$daemon_installed")",
      "Available": "$(esc "$daemon_available")",
      "Changelog": "https://github.com/samcharles93/archie-core/blob/main/CHANGELOG.archied.md"
    },
    {
      "ID": "agent",
      "Label": "Runtime",
      "Installed": "$(esc "$agent_installed")",
      "Available": "$(esc "$agent_available")",
      "Changelog": "https://github.com/samcharles93/archie-core/blob/main/CHANGELOG.archie.md"
    }
  ],
  "Deferred": false
}
EOF
