#!/bin/sh
# migrate-v0220.sh — ONE-TIME claude-spt update-channel migration (ADR-0008 relocation).
# Patches the INSTALLED adapter's [update].repo to the private home, then pulls v0.22.0+
# through the normal `spt adapter update` path. Run once per node; endpoints need no action
# (the new adapter rides each endpoint's next start). Distributed via the migration/v0.22.0
# branch and internal announcement — never via a committed pointer in the public repo.
# Usage:  gh api -H "Accept: application/vnd.github.raw" \
#           "/repos/BigscreenVR/claude-spt-bs/contents/migrate-v0220.sh?ref=migration/v0.22.0" | sh
# [impl->REQ-DIST-MIGRATION-SCRIPT]
set -u
OLD='repo = "SaberMage/claude-spt"'
NEW='repo = "BigscreenVR/claude-spt-bs"'

command -v spt >/dev/null 2>&1 || { echo "FAIL: spt CLI not found on PATH" >&2; exit 1; }
command -v gh  >/dev/null 2>&1 || { echo "FAIL: gh CLI required (authenticated, with access to BigscreenVR/claude-spt-bs)" >&2; exit 1; }

line=$(spt adapter list 2>/dev/null | grep '^claude-spt:' | head -n1)
[ -n "$line" ] || { echo "FAIL: claude-spt adapter not installed on this node" >&2; exit 1; }
dir=$(printf '%s\n' "$line" | sed -n 's/.*(from \(.*\)).*/\1/p')
mf="$dir/manifest.toml"
[ -f "$mf" ] || { echo "FAIL: installed manifest not found: $mf" >&2; exit 1; }

if grep -q 'BigscreenVR/claude-spt-bs' "$mf"; then
  echo "already migrated: $mf points at the private home"
else
  grep -q "$OLD" "$mf" || { echo "FAIL: unexpected [update].repo in $mf — migrate by hand" >&2; exit 1; }
  cp "$mf" "$mf.pre-migration" || exit 1
  sed -i "s#$OLD#$NEW#" "$mf" || { echo "FAIL: patch failed; original kept at $mf.pre-migration" >&2; exit 1; }
  echo "patched: [update].repo -> BigscreenVR/claude-spt-bs (backup: $mf.pre-migration)"
fi

spt adapter update claude-spt || {
  echo "FAIL: spt adapter update claude-spt failed — manifest backup at $mf.pre-migration" >&2; exit 1; }
ver=$(spt adapter version claude-spt 2>/dev/null)
echo "claude-spt now at: $ver (updates ride the private home from here on)"
