#!/bin/sh
# Instala el agente de Onetty (onetty 22ef4211f78a): Node, tmux y la
# app en ~/.local/share/onetty, sin root. Claude Code se instala aparte.
#   curl -fsSL <app>/install.sh | sh -s -- [--token … [--owner …]] [--name nombre]
# El hub es siempre hub.onetty.app.
set -eu
VERSION='22ef4211f78a'
X64_URL='https://storage.googleapis.com/chalar-erp-paneo-dl/agent/onetty-agent-22ef4211f78a-linux-x64.tar.gz'
X64_SHA='e44112e856808ff5dd2347fe238bd884e85a9f2aedcf8ee7076e83f88ad321fa'
ARM64_URL='https://storage.googleapis.com/chalar-erp-paneo-dl/agent/onetty-agent-22ef4211f78a-linux-arm64.tar.gz'
ARM64_SHA='c3b740e854853a2d7bea8048053c22f76b8de76248bbffdfec7634919186e73f'
MAC_URL='https://storage.googleapis.com/chalar-erp-paneo-dl/agent/onetty-agent-22ef4211f78a-darwin-arm64.tar.gz'
MAC_SHA='f779f2e3cdd1d94fd80a2e83fe8c3569e9e69a5887bb5317edce934fc3dc6e09'
ROOT="${ONETTY_HOME:-$HOME/.local/share/onetty}"
BIN="$HOME/.local/bin"

fail() { echo "✗ $*" >&2; exit 1; }

# todo adentro de main: con curl | sh, sh lee el script entero antes de
# correr nada (ni un hijo que lea stdin ni una descarga cortada lo rompen)
main() {
  TOKEN='' OWNER='' NAME=''
  while [ $# -gt 0 ]; do
    case "$1" in
      --token) TOKEN=$2; shift 2 ;;
      --owner) OWNER=$2; shift 2 ;;
      --name) NAME=$2; shift 2 ;;
      *) fail "opción desconocida: $1" ;;
    esac
  done

  case "$(uname -s)-$(uname -m)" in
    Linux-x86_64|Linux-amd64) URL=$X64_URL; SHA=$X64_SHA ;;
    Linux-aarch64|Linux-arm64) URL=$ARM64_URL; SHA=$ARM64_SHA ;;
    Darwin-arm64)
      URL=$MAC_URL; SHA=$MAC_SHA
      # tmux de Homebrew (el paquete de Linux lo trae; el de macOS no)
      [ -x /opt/homebrew/bin/brew ] && PATH="/opt/homebrew/bin:$PATH"
      command -v tmux >/dev/null 2>&1 || { command -v brew >/dev/null 2>&1 && brew install tmux; }         || fail "falta tmux: instalá Homebrew (https://brew.sh) y corré brew install tmux"
      ;;
    Darwin-*) fail "en macOS solo Apple Silicon (M1 o posterior)" ;;
    *) fail "sistema no soportado: $(uname -s) $(uname -m)" ;;
  esac
  [ -n "$URL" ] || fail "no hay paquete para $(uname -m)"
  for c in curl tar; do command -v $c >/dev/null 2>&1 || fail "falta $c"; done
  if command -v sha256sum >/dev/null 2>&1; then SUM='sha256sum'; else SUM='shasum -a 256'; fi

  mkdir -p "$ROOT/versions" "$BIN"
  if [ ! -f "$ROOT/versions/$VERSION/app/bundle.json" ]; then
    TMP=$(mktemp -d "$ROOT/.dl-XXXXXX")
    trap 'rm -rf "$TMP"' EXIT
    echo "→ bajando onetty $VERSION…"
    curl -fsSL "$URL" -o "$TMP/p.tar.gz"
    [ "$($SUM "$TMP/p.tar.gz" | cut -d' ' -f1)" = "$SHA" ] || fail "el paquete no coincide con el sha256 publicado"
    mkdir "$TMP/x"
    tar -xzf "$TMP/p.tar.gz" -C "$TMP/x"
    rm -rf "$ROOT/versions/$VERSION"
    mv "$TMP/x" "$ROOT/versions/$VERSION"
  fi
  # cambio atómico del enlace (macOS: mv no tiene -T; -h no sigue el enlace viejo)
  ln -sfn "versions/$VERSION" "$ROOT/current.new"
  if mv -T "$ROOT/current.new" "$ROOT/current" 2>/dev/null; then :; else rm -f "$ROOT/current"; mv "$ROOT/current.new" "$ROOT/current"; fi

  # el comando: siempre la versión activa
  rm -f "$BIN/onetty"
  printf '#!/bin/sh\nexec "%s" "%s" "$@"\n' "$ROOT/current/node/bin/node" "$ROOT/current/app/src/index.js" > "$BIN/onetty"
  chmod 755 "$BIN/onetty"
  CS="$BIN/onetty"
  case ":$PATH:" in *":$BIN:"*) ;; *) PATH="$BIN:$PATH"; export PATH ;; esac
  echo "✓ onetty $VERSION en $ROOT"

  if [ -n "$TOKEN" ]; then
    "$CS" agent enroll --token "$TOKEN" ${OWNER:+--owner "$OWNER"} ${NAME:+--name "$NAME"} </dev/null
  fi
  # ONETTY_NO_SETUP=1: solo instalar (tests)
  if [ -z "${ONETTY_NO_SETUP:-}" ]; then
    "$CS" setup --yes ${NAME:+--name "$NAME"} </dev/null
    # recién dado de alta: que serve se conecte al hub
    if [ -n "$TOKEN" ]; then
      if [ "$(uname -s)" = Darwin ]; then launchctl kickstart -k "gui/$(id -u)/app.onetty.serve" 2>/dev/null || true
      else systemctl --user try-restart onetty 2>/dev/null || true; fi
    fi
  fi

  case "$(command -v onetty || true)" in
    "$CS"|'') ;;
    *) echo "Ojo: en tu PATH, onetty es $(command -v onetty) (una instalación anterior). Sacala o poné $BIN primero." ;;
  esac
}

main "$@"
