#!/usr/bin/env bash
# session-bridge field-node bootstrap.
#   curl -fsSL https://bridge.oxmelater.com/setup.sh | bash
#
# PUBLIC script, NO secrets. Access to the private repo comes from a deploy key this
# script generates on THIS box and the operator registers on trjtk/session-bridge.
# A leaked copy of this script grants nothing. Safe to host on a public Cloudflare Page.
set -u

REPO="git@github.com:trjtk/session-bridge.git"
DEST="${SESSION_BRIDGE_DIR:-$HOME/session-bridge}"
KEY="$HOME/.ssh/session_bridge"

say(){ printf '\n\033[1m%s\033[0m\n' "$*"; }
ttyread(){ if [ -r /dev/tty ]; then read -r "$@" < /dev/tty; else read -r "$@"; fi; }

say "session-bridge — field-node bootstrap"

# 1. prereqs
miss=""; for c in git ssh ssh-keygen bash curl; do command -v "$c" >/dev/null 2>&1 || miss="$miss $c"; done
[ -n "$miss" ] && { echo "Missing required tools:$miss — install them and re-run."; exit 1; }
if command -v tmux >/dev/null 2>&1; then echo "tmux: present (event-driven nudges enabled)"; else echo "tmux: absent (ntfy/manual reads only)"; fi

# 2. identity for this node
DEFID="pentest@kali-$(hostname -s 2>/dev/null || hostname 2>/dev/null || echo node)"
printf 'Bridge identity for this node [%s]: ' "$DEFID"; ttyread SID; SID="${SID:-$DEFID}"

# 3. dedicated key (idempotent)
if [ -f "$KEY" ]; then
  echo "Reusing existing bridge key: $KEY"
else
  ssh-keygen -t ed25519 -f "$KEY" -N "" -C "session-bridge $(hostname 2>/dev/null)" >/dev/null
  echo "Generated bridge key: $KEY"
fi

say "DEPLOY KEY — give this PUBLIC key to the operator:"
echo "------------------------------------------------------------------"
cat "$KEY.pub"
echo "------------------------------------------------------------------"
cat <<EOF
Operator: register it as a WRITE-ENABLED deploy key on trjtk/session-bridge:
  GitHub -> repo -> Settings -> Deploy keys -> Add deploy key
  -> paste the key -> CHECK "Allow write access" -> Add.
  (or from the workstation: gh repo deploy-key add <pubkey-file> \\
     --repo trjtk/session-bridge --allow-write --title "$SID")
EOF
printf '\nPress Enter once the deploy key is registered (I will then clone)... '; ttyread _

# 4. clone, retrying until the key is live
export GIT_SSH_COMMAND="ssh -i $KEY -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new"
if [ -d "$DEST/.git" ]; then
  echo "Repo already present at $DEST — updating."; git -C "$DEST" pull -q || true
else
  ok=0
  for i in 1 2 3 4 5 6 7 8; do
    if git clone -q "$REPO" "$DEST" 2>/dev/null; then ok=1; break; fi
    echo "  clone failed (deploy key not active yet?) — retry $i/8 in 15s"; sleep 15
  done
  [ "$ok" = 1 ] || { echo "Could not clone. Confirm the deploy key has WRITE access, then re-run this script."; exit 1; }
fi
cd "$DEST" || exit 1
git config core.sshCommand "ssh -i $KEY -o IdentitiesOnly=yes"
git config user.name  "kali-node"
git config user.email "$SID"

# 5. configure this node's identity (+ auto-detect our tmux pane for nudges)
[ -f config/session.env ] || cp config/session.env.example config/session.env
TGT="$(tmux display-message -p '#{session_name}:#{window_index}.#{pane_index}' 2>/dev/null || true)"
sed -i.bak "s|^SESSION_ID=.*|SESSION_ID=$SID|; s|^BRIDGE_TMUX_TARGET=.*|BRIDGE_TMUX_TARGET=$TGT|" config/session.env && rm -f config/session.env.bak
chmod +x bin/*.sh

# 6. start the watcher + announce
pgrep -f bridge-watch.sh >/dev/null 2>&1 || { nohup bash bin/bridge-watch.sh >/tmp/bridge-watch.log 2>&1 & echo "watcher started (pid $!), log /tmp/bridge-watch.log"; }
bash bin/bridge-send.sh --to home@hq --thread setup --kind discussion -- \
  "Field node $SID online — bootstrapped via setup.sh, watcher running. Ready for tasking." || \
  echo "(hello send failed — check the deploy key has WRITE access)"

say "Done. This node = $SID at $DEST"
cat <<EOF
Next: in the Claude Code session on THIS box, read $DEST/prompts/bridge-loop.md as
your standing instruction so you act on bridge messages (read/answer/relay).
Only act in-scope + authorized. Everything sent is retained in git history.
EOF
