#!/bin/sh
# newer-version A B — echo whichever of two dotted versions sorts higher.
# Equal versions echo A. Missing components count as zero, so 0.9 == 0.9.0.
#
# Exists because two callers need ordering rather than equality:
#   - bin/doctor, comparing the installed plugin generation against the newest
#     manifest on the host (#30);
#   - task check, which must fail when plugin.json is BEHIND the latest tag and
#     stay quiet when it is ahead — the normal state on a checkout that has not
#     fetched the tag CI just pushed (#34).
#
# sort -V would do it in one line and is not portable enough for this fleet.

set -u

[ $# -eq 2 ] || { echo "usage: newer-version A B" >&2; exit 2; }

printf '%s\n%s\n' "$1" "$2" | awk -F. '
  { raw[NR] = $0; for (i = 1; i <= 3; i++) n[NR, i] = ($i == "" ? 0 : $i + 0) }
  END {
    for (i = 1; i <= 3; i++) {
      if (n[1, i] > n[2, i]) { print raw[1]; exit }
      if (n[1, i] < n[2, i]) { print raw[2]; exit }
    }
    print raw[1]
  }'
