#!/usr/bin/env bash
# Checks npm for newer gowalk-cicd and preserves an isolated update candidate.
# Exits 0 on no-op or package-install failure; unconfirmed source preservation fails.
#
# DESIGN DECISION (intentional, not a bug):
# This script runs `npx --yes gowalk-cicd@<latest>` on every default-
# branch CI run with `permissions: contents: write`. That means the consumer
# repo trusts whatever code gowalk-cicd publishes to npm.
#
# Trust model — internally consistent with the rest of the action:
#   - Consumers initially install via the same `npx --yes gowalk-cicd`
#     command. They've already accepted the trust relationship.
#   - The package is published from gowalk-cicd via a dedicated GitHub Actions
#     workflow using npm Trusted Publishing (OIDC after initial bootstrap).
#     Compromise of that release workflow would already be catastrophic
#     regardless of this autoupdate path.
#   - We pin to the exact version returned by `npm view` immediately above
#     (`@$latest`) so the small TOCTOU window between view and exec can't
#     swap a different version.
#   - Consumers who want to pin can set `with: { auto-update: 'false' }` in
#     their workflow.
#
# Hardening considered, not adopted:
#   - `npm audit signatures` provenance check: requires npm to have published
#     with --provenance, which the gowalk-cicd publish workflow does not currently
#     emit. Worth revisiting if/when gowalk-cicd enables provenance.
#   - Pinning to a fixed hash: defeats the autoupdate purpose.
#   - Out-of-band verification (signed manifest): overkill for the threat
#     model described above.
set -euo pipefail

VERSION_FILE=".github/actions/swift-app/.daemux-version"
PKG="gowalk-cicd"

current=""
if [[ -f "$VERSION_FILE" ]]; then
  current="$(tr -d '[:space:]' < "$VERSION_FILE")"
fi

if ! latest="$(npm view "$PKG" version 2>/dev/null)"; then
  echo "::warning::autoupdate: failed to query npm for $PKG"
  exit 0
fi
latest="$(printf '%s' "$latest" | tr -d '[:space:]')"

if [[ -z "$latest" ]]; then
  echo "::warning::autoupdate: empty version returned for $PKG"
  exit 0
fi

if [[ "$current" == "$latest" ]]; then
  echo "autoupdate: $PKG already at $latest"
  exit 0
fi

# The runner reparses local action.yml files for post hooks and reuses the step IDs
# it cached before execution. Updating these files in place can change their step
# count and crash cleanup. Publish the update candidate from a detached worktree;
# the current job keeps its exact manifests, scripts, index and uncommitted source.
echo "autoupdate: $PKG $current -> $latest; preparing an isolated source candidate"
exec python3 "$(dirname "$0")/autoupdate_stage.py" "$latest"
