#!/bin/sh
# rbtop — connect to apricot and run btop (transient dnf install on first run).
#
# Prefers mosh over ssh when both ends have it (better resilience for the
# interactive TUI under sleep/roam/network blips). Override with
# RBTOP_TRANSPORT=ssh to force ssh.

set -eu

HOST=${RBTOP_HOST:-apricot.lan}
INNER='sudo dnf install -y --transient btop && btop'

# Reuse rclaude's auto-installer for shared deps (mosh, etc.). Idempotent —
# the marker in ~/.cache/rclaude/ skips re-running on every invocation.
if command -v rclaude >/dev/null 2>&1; then
    rclaude install --on "$HOST" >&2 || true
fi

case ${RBTOP_TRANSPORT:-auto} in
    ssh)  use=ssh ;;
    mosh) use=mosh ;;
    *)
        use=ssh
        if command -v mosh >/dev/null 2>&1 \
           && ssh -o BatchMode=yes -o ConnectTimeout=3 "$HOST" 'command -v mosh-server' >/dev/null 2>&1; then
            use=mosh
        fi
        ;;
esac

if [ "$use" = mosh ]; then
    exec mosh "$HOST" -- sh -c "$INNER"
else
    exec ssh -t -o ServerAliveInterval=30 -o ServerAliveCountMax=6 "$HOST" "$INNER"
fi
