#!/bin/bash
# agentsesh: list, resume and manage persistent tmux sessions from any terminal.
# These are the same sessions the AgentSesh iPhone and iPad app shows.
export PATH="/opt/homebrew/bin:/usr/local/bin:$HOME/.local/bin:$PATH"
[ -n "${LANG:-}" ] || export LANG=en_US.UTF-8
export COLORTERM=truecolor
HOSTS_FILE="$HOME/.config/agentsesh/hosts"
REMOTE_ENV='export PATH="/opt/homebrew/bin:/usr/local/bin:$HOME/.local/bin:$PATH"; [ -n "$LANG" ] || export LANG=en_US.UTF-8; export COLORTERM=truecolor;'
SEP='|||'

me() { scutil --get LocalHostName 2>/dev/null || hostname -s; }

# Nothing of AgentSesh runs in the background. Devices reach this machine through its own SSH and
# tmux starts on demand, so what must hold is: SSH on, the machine awake, and the kit installed.
doctor() {
  bad=0
  ok() { printf '  ok    %s\n' "$*"; }
  fix() { printf '  FIX   %s\n' "$*"; bad=1; }
  echo "AgentSesh on $(me) ($(uname -s))"
  if command -v tmux >/dev/null 2>&1; then ok "tmux $(tmux -V | cut -d' ' -f2)"; else fix "tmux missing: set up again from the app, or run scripts/install-host.sh"; fi
  if [ -f "$HOME/.config/agentsesh/tmux.conf" ] && grep -qxF "source-file -q ~/.config/agentsesh/tmux.conf" "$HOME/.tmux.conf" 2>/dev/null; then ok "terminal profile"; else fix "terminal profile not installed: set up again"; fi
  if [ -x "$HOME/.config/agentsesh/end-session.sh" ]; then ok "end-session (ending a session leaves nothing behind)"; else fix "end-session.sh missing: set up again"; fi
  case ":$PATH:" in *":$HOME/.local/bin:"*) ok "agentsesh on PATH" ;; *) fix "add ~/.local/bin to PATH in your shell profile" ;; esac
  for a in claude codex agy; do
    if command -v "$a" >/dev/null 2>&1; then ok "$a found"; else printf '  -     %s not installed\n' "$a"; fi
  done
  if [ "$(uname -s)" = Darwin ]; then
    if nc -z -G 2 127.0.0.1 22 >/dev/null 2>&1; then ok "Remote Login (SSH) on"; else fix "turn on System Settings > General > Sharing > Remote Login"; fi
    s=$(pmset -g 2>/dev/null | awk '$1 == "sleep" { print $2 }')
    amph=$(pmset -g assertions 2>/dev/null | grep -c 'Amphetamine.*PreventUserIdleSystemSleep\|(Amphetamine).*PreventUserIdleSystemSleep')
    if [ "$s" = 0 ] && [ "$amph" -gt 0 ]; then ok "kept awake by an Amphetamine session"
    elif [ "$s" = 0 ]; then ok "never sleeps on its own"
    elif [ "$amph" -gt 0 ]; then ok "kept awake by an Amphetamine session (the system would sleep after $s min without it)"
    else
      held=$(pmset -g 2>/dev/null | sed -n 's/^ *sleep .*(sleep prevented by \(.*\))/\1/p')
      fix "sleeps after ${s:-?} min idle, which pauses sessions and makes it unreachable${held:+. Awake right now only because of: $held}. Start an Amphetamine session (Indefinitely), or run: sudo pmset -a sleep 0"
    fi
  else
    if systemctl is-active --quiet ssh 2>/dev/null || systemctl is-active --quiet sshd 2>/dev/null; then ok "SSH running"; else fix "SSH not running. Run: sudo systemctl enable --now ssh"; fi
    m=$(systemctl is-enabled suspend.target 2>/dev/null)
    g=$(gsettings get org.gnome.settings-daemon.plugins.power sleep-inactive-ac-type 2>/dev/null)
    if [ "$m" = masked ]; then ok "suspend disabled"
    elif [ -n "$g" ] && [ "$g" != "'nothing'" ]; then fix "the desktop suspends when idle ($g). Run: sudo systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target"
    else ok "no idle suspend configured (suspend.target ${m:-unknown})"; fi
  fi
  if [ -f /etc/ssh/sshd_config.d/050-agentsesh.conf ]; then ok "SSH drops dead phone connections within a minute"
  else fix "SSH keeps dead phone connections for hours, and macOS refuses everyone once enough pile up. Run once: sudo sh ~/.config/agentsesh/sshd-setup.sh"; fi
  n=$(ps ax -o command= 2>/dev/null | grep -cE '^sshd(-session)?: [^ ]+@notty')
  if [ "$n" -gt 30 ]; then fix "$n background SSH connections open. If new ones are refused, close them: sudo pkill -f 'sshd-session: $(id -un)@notty'"
  else ok "$n background SSH connections"; fi
  echo "Sessions live in tmux and end if this machine restarts."
  return $bad
}

usage() { cat <<USAGE
agentsesh list                    live sessions on this Mac
agentsesh                         list them and pick one to resume
agentsesh resume <name|number>    resume a session (or just: agentsesh <name>)
agentsesh all                     live sessions on every machine
agentsesh <host>:<name>           resume or start one on another machine
agentsesh new [--yolo] [claude|codex|agy|shell] [folder] [name]
                                  start a session here and open it (--yolo skips permission prompts)
agentsesh rename <name> <new>     rename a session
agentsesh kill <name>             end a session and everything in it
agentsesh doctor                  check this machine is ready: SSH, sleep, tmux, profile
agentsesh leave                   leave this session running (also: Ctrl-b d)
agentsesh enroll [public-key]     authorize a device key on every machine (default: clipboard)
USAGE
}

rows() {
  tmux list-panes -a -f '#{&&:#{window_active},#{pane_active}}' \
    -F "#{session_name}$SEP#{session_attached}$SEP#{pane_tty}$SEP#{window_activity}$SEP#{pane_current_path}$SEP#{pane_title}" 2>/dev/null
}

agent_of() {
  ps -t "${1#/dev/}" -o command= 2>/dev/null | awk '{for(i=1;i<=2&&i<=NF;i++){n=$i;sub(/.*\//,"",n);if(n=="claude"||$i~/\/claude\/versions\//)c=1;if(n=="codex")x=1;if(n=="agy"||n=="antigravity")g=1}}END{if(c)print "claude";else if(x)print "codex";else if(g)print "agy";else print "shell"}'
}

ago() {
  local s=$(( $(date +%s) - $1 ))
  if [ "$s" -lt 60 ]; then echo "now"
  elif [ "$s" -lt 3600 ]; then echo "$((s / 60))m ago"
  elif [ "$s" -lt 86400 ]; then echo "$((s / 3600))h ago"
  else echo "$((s / 86400))d ago"; fi
}

short_path() { case $1 in "$HOME") echo "~" ;; "$HOME"/*) echo "~/${1#"$HOME"/}" ;; *) echo "$1" ;; esac; }

list() {
  local data; data=$(rows)
  if [ -z "$data" ]; then
    echo "No live sessions on $(me). Start one: agentsesh new claude"
    return 1
  fi
  printf '%3s  %-28s %-7s %-9s %-9s %s\n' '#' NAME AGENT ACTIVE OPEN FOLDER
  local i=0
  while IFS= read -r line; do
    i=$((i + 1))
    local name=${line%%"$SEP"*}; line=${line#*"$SEP"}
    local attached=${line%%"$SEP"*}; line=${line#*"$SEP"}
    local tty=${line%%"$SEP"*}; line=${line#*"$SEP"}
    local active=${line%%"$SEP"*}; line=${line#*"$SEP"}
    local path=${line%%"$SEP"*}
    local branch; branch=$(GIT_OPTIONAL_LOCKS=0 git -C "$path" symbolic-ref --short -q HEAD 2>/dev/null)
    local open="-"; [ "$attached" -gt 0 ] && open="$attached device"; [ "$attached" -gt 1 ] && open="${open}s"
    printf '%3d  %-28s %-7s %-9s %-9s %s%s\n' "$i" "$name" "$(agent_of "$tty")" "$(ago "$active")" "$open" "$(short_path "$path")" "${branch:+  ($branch)}"
  done <<<"$data"
}

name_at() { rows | awk -F'\\|\\|\\|' -v n="$1" 'NR==n{print $1}'; }
safe_name() { printf %s "$1" | LC_ALL=C tr -cs 'A-Za-z0-9_-' '-' | sed 's/^-*//;s/-*$//'; }

# Opening a session takes it over: any other screen showing it (the phone, an iPad, another
# terminal) lets go, and the session continues here at this terminal's size. No lock files.
attach() {
  if [ -n "${TMUX:-}" ]; then
    me=$(tmux display -p '#{client_name}')
    tmux switch-client -t "=$1" || return 1
    tmux list-clients -t "=$1" -F '#{client_name}' 2>/dev/null | while IFS= read -r c; do
      [ "$c" = "$me" ] || tmux detach-client -t "$c"
    done
    return 0
  fi
  tmux -u attach-session -d -t "=$1" || return 1
  if tmux has-session -t "=$1" 2>/dev/null && [ "$(tmux display -p -t "=$1:" '#{session_attached}')" -gt 0 ]; then
    echo "$1 continued on another device. To take it back here: agentsesh $1"
  fi
}

resume() {
  case $1 in
    '') usage; exit 2 ;;
    *[!0-9]*) ;;
    *) local n; n=$(name_at "$1"); [ -n "$n" ] && { attach "$n"; return; } ;;
  esac
  if tmux has-session -t "=$1" 2>/dev/null; then attach "$1"
  else echo "No session named '$1'. See: agentsesh list" >&2; exit 1; fi
}

new_session() {
  local yolo=0 args=()
  for arg in "$@"; do
    case $arg in
      --yolo|--skip-permissions|--dangerously-skip-permissions) yolo=1 ;;
      *) args+=("$arg") ;;
    esac
  done
  kind=${args[0]:-shell}; dir=${args[1]:-$PWD}
  case $kind in
    claude|codex|agy|shell) ;;
    antigravity) kind=agy ;;
    *) echo "Choose claude, codex, agy or shell." >&2; exit 2 ;;
  esac
  name=$(safe_name "${args[2]:-$kind-$(basename "$dir")}")
  [ -n "$name" ] || name=$kind
  base=$name; n=2
  while tmux has-session -t "=$name" 2>/dev/null; do name="$base-$n"; n=$((n + 1)); done
  tmux -u new-session -d -s "$name" -c "$dir" || exit 1
  local cmd=""
  case "$kind:$yolo" in
    claude:1) cmd="claude --dangerously-skip-permissions" ;;
    claude:0) cmd="claude" ;;
    codex:1)  cmd="codex --yolo" ;;
    codex:0)  cmd="codex" ;;
    agy:1)    cmd="agy --dangerously-skip-permissions" ;;
    agy:0)    cmd="agy" ;;
  esac
  [ -z "$cmd" ] || tmux send-keys -t "=$name:" "$cmd" Enter
  attach "$name"
}

is_self() {
  [ "$1" = "$(hostname -s)" ] || { command -v scutil >/dev/null 2>&1 && [ "$1" = "$(scutil --get LocalHostName 2>/dev/null)" ]; }
}
hosts() {
  if [ -f "$HOSTS_FILE" ]; then grep -vE '^\s*(#|$)' "$HOSTS_FILE"
  else hostname -s
}

case "${1:-}" in
  -h|--help|help) usage ;;
  doctor|check) doctor ;;
  list|ls) list || true ;;  # nothing running is an answer, not an error
  "")
    list || exit 0
    printf 'Resume which? (number or name, Return to cancel) '; read -r pick || exit 0
    [ -n "$pick" ] && resume "$pick" ;;
  resume|attach|open) resume "${2:-}" ;;
  all)
    for h in $(hosts); do
      echo "== $h"
      if is_self "$h"; then list
      else ssh -o ConnectTimeout=4 -o BatchMode=yes "$h" "$REMOTE_ENV agentsesh list 2>/dev/null || tmux list-sessions -F '   #{session_name}' 2>/dev/null; true" || echo "   not reachable"
      fi
    done ;;
  new) shift; new_session "$@" ;;
  rename) tmux rename-session -t "=$2" "$(safe_name "$3")" ;;
  kill|end) [ -n "${2:-}" ] || { usage; exit 2; }
    # Everything started in it ends too, the same as ending it in the app.
    if [ -x "$HOME/.config/agentsesh/end-session.sh" ]; then "$HOME/.config/agentsesh/end-session.sh" "$2" tmux || exit $?
    else tmux kill-session -t "=$2" || exit $?; fi
    echo "Ended $2." ;;
  leave|detach) tmux detach-client ;;
  enroll)
    key=${2:-$(pbpaste 2>/dev/null)}
    case $key in
      ssh-ed25519\ *) ;;
      *) echo "Not an ssh-ed25519 public key. Copy it from AgentSesh > Settings, then run: agentsesh enroll" >&2; exit 2 ;;
    esac
    if printf %s "$key" | grep -qvE '^ssh-ed25519 [A-Za-z0-9+/=]+( [A-Za-z0-9@._ -]*)?$'; then
      echo "Refusing: key contains unexpected characters." >&2; exit 2
    fi
    for h in $(hosts); do
      printf '%-22s ' "$h"
      add='umask 077; mkdir -p ~/.ssh; touch ~/.ssh/authorized_keys; IFS= read -r k; grep -qxF "$k" ~/.ssh/authorized_keys || printf "%s\n" "$k" >> ~/.ssh/authorized_keys; echo authorized'
      if is_self "$h"; then printf '%s\n' "$key" | sh -c "$add"
      else printf '%s\n' "$key" | ssh -o ConnectTimeout=4 -o BatchMode=yes "$h" "$add" || echo "not reachable"
      fi
    done ;;
  *:*) h=${1%%:*}; n=${1#*:}; exec ssh -t "$h" "$REMOTE_ENV exec tmux -u new-session -A -s '$(safe_name "$n")'" ;;
  *)
    if tmux has-session -t "=$1" 2>/dev/null; then attach "$1"; else new_session shell "$PWD" "$1"; fi ;;
esac
