#!/bin/sh
# Sign the Admin's agy CLI in to the Google Antigravity subscription (Gemini 4
# Neon), show the sign-in and quota, or sign out. Run as root on the Admin:
#
#   sellable-admin-antigravity login    # agy's own Google sign-in
#   sellable-admin-antigravity status   # signed in? quota left
#   sellable-admin-antigravity logout   # back to Codex first
#
# The sign-in lands on the Admin volume (HOME=/opt/data, as the hermes user)
# and agy refreshes it there. After login or logout, press Refresh Agent so the
# Admin rebuilds its model chain: Antigravity first while signed in, otherwise
# Codex first. agy only ever sees a minimal environment.
set -eu
dir=/opt/data/.gemini/antigravity-cli
token="${dir}/antigravity-oauth-token"

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

status() {
  if [ ! -s "${token}" ]; then
    echo "agy is not signed in on this Admin."
    return 1
  fi
  as_hermes /usr/local/bin/agy -p "/usage" --output-format text </dev/null
}

case "${1:-status}" in
  login)
    install -d -o hermes -g hermes -m 0700 /opt/data/.gemini "${dir}"
    echo "Choose '1. Google OAuth', open the URL on your own computer, sign in,"
    echo "and paste the code back here. Once agy says you are signed in, leave"
    echo "it with Ctrl+C. Then press Refresh Agent."
    as_hermes /usr/local/bin/agy || true
    status
    ;;
  status)
    status
    ;;
  logout)
    rm -f "${token}"
    echo "Signed out. Press Refresh Agent to put Codex first again."
    ;;
  *)
    echo "usage: sellable-admin-antigravity login|status|logout" >&2
    exit 2
    ;;
esac
