#!/usr/bin/env bash
set -euo pipefail
ab() { npx --yes agent-browser --session issue7568-after "$@"; }
inspect() {
  ab eval '(async () => {const c=JSON.parse(await window.desktopBridge.getConnectionCatalog());const p=c.profiles.find(p=>p.target?.alias==="issue-7568-repro");const b=await window.desktopBridge.ensureSshEnvironment(p.target,{issuePairingToken:false});const d=await window.desktopBridge.fetchSshEnvironmentDescriptor(b.httpBaseUrl);const saved=JSON.parse(await window.desktopBridge.getConnectionCatalog()).profiles.find(x=>x.connectionId===p.connectionId);if(saved.target.port!==null||saved.target.hostname!=="issue-7568-repro")throw new Error("alias intent pinned");return {connectionId:p.connectionId,expectedEnvironmentId:p.environmentId,descriptor:d.environmentId??d.id,resolvedTarget:b.target,savedTarget:saved.target,profileCount:c.profiles.length};})()'
}
date -u
inspect
for port in 24571 24572; do
  ab find role switch click --name 'Switch off fs-28' --exact
  python3 - "$port" <<'PY'
from pathlib import Path
import re,sys
port=sys.argv[1]
p=Path.home()/'.ssh/config';p.write_text(re.sub(r'(?m)^  Port \d+$','  Port '+port,p.read_text()))
p=Path('/tmp/issue-7568-ssh/sshd_config');p.write_text(re.sub(r'(?m)^Port \d+$','Port '+port,p.read_text()))
PY
  sudo -n kill -HUP "$(cat /tmp/issue-7568-ssh/sshd.pid)"
  ssh -o BatchMode=yes issue-7568-repro 'printf "terminal-alias-connected\n"'
  ab find role switch click --name 'Switch on fs-28' --exact
  inspect
  ab snapshot -i
  date -u
done
