#!/bin/sh
# Sign one machine in to a plan, with the provider's own program and its own
# sign-in. Run as root on that machine:
#
#   sellable-model-signin claude login|status|logout
#   sellable-model-signin agy    login|status|logout
#
# Only Sellable's own machines: whoever can use the machine's agent could read
# the sign-in. After login or logout, press Refresh Agent. The model is used
# where the model order page names it.
set -eu
root=/opt/data/model-signins
claude_version=2.1.333
agy_version=1.5.22
agy_url=https://storage.googleapis.com/antigravity-public/antigravity-cli/1.5.22-5241614164164608/linux-x64/cli_linux_x64.tar.gz
agy_sha512=eeaee801572073a8fa8c1b9faaac62fd2d7e9b76e8b9bd27d5f14707cfa5c64ee8661e08e57ebba8a25efe0714c5fe9d029a29e0412c352eb6714c9699d1fb35
claude_dir="${root}/claude"
claude_bin="${root}/claude-code/node_modules/.bin/claude"
agy_bin="${root}/agy/agy"
agy_dir=/opt/data/.gemini/antigravity-cli

as_hermes() {
  /command/s6-setuidgid hermes env -i PATH=/usr/local/bin:/usr/bin:/bin \
    HOME=/opt/data TERM="${TERM:-xterm-256color}" USER=hermes "$@"
}

install_claude() {
  if [ -x "${claude_bin}" ] && [ "$(as_hermes "${claude_bin}" --version | cut -d' ' -f1)" = "${claude_version}" ]; then
    return 0
  fi
  install -d -o hermes -g hermes -m 0700 "${root}" "${root}/claude-code"
  as_hermes npm install --prefix "${root}/claude-code" --no-audit --no-fund --save-exact "@anthropic-ai/claude-code@${claude_version}"
}

install_agy() {
  if [ -x "${agy_bin}" ] && [ "$(as_hermes "${agy_bin}" --version)" = "${agy_version}" ]; then
    return 0
  fi
  work="$(mktemp -d)"
  curl --retry 5 -fsSL "${agy_url}" -o "${work}/agy.tar.gz"
  printf '%s  %s\n' "${agy_sha512}" "${work}/agy.tar.gz" | sha512sum -c -
  tar -xzf "${work}/agy.tar.gz" -C "${work}" antigravity
  install -d -o hermes -g hermes -m 0700 "${root}" "${root}/agy"
  install -o hermes -g hermes -m 0500 "${work}/antigravity" "${agy_bin}"
  rm -rf "${work}"
}

case "${1:-}:${2:-}" in
  claude:login)
    install_claude
    install -d -o hermes -g hermes -m 0700 "${claude_dir}"
    as_hermes CLAUDE_CONFIG_DIR="${claude_dir}" "${claude_bin}" auth login
    ;;
  claude:status)
    as_hermes CLAUDE_CONFIG_DIR="${claude_dir}" "${claude_bin}" auth status
    ;;
  claude:logout)
    as_hermes CLAUDE_CONFIG_DIR="${claude_dir}" "${claude_bin}" auth logout
    ;;
  agy:login)
    install_agy
    install -d -o hermes -g hermes -m 0700 /opt/data/.gemini "${agy_dir}"
    echo "Choose '1. Google OAuth', open the URL on your own computer, paste the"
    echo "code back here, and leave with Ctrl+C once agy says you are signed in."
    as_hermes "${agy_bin}" || true
    ;;
  agy:status)
    as_hermes "${agy_bin}" -p "/usage" --output-format text </dev/null
    ;;
  agy:logout)
    rm -f "${agy_dir}/antigravity-oauth-token"
    ;;
  *)
    echo "usage: sellable-model-signin claude|agy login|status|logout" >&2
    exit 2
    ;;
esac
