#!/bin/sh
# Fornace — authorize Google services for this operator's own account.
#
# One browser consent (your fornacestudio.com Google account) lets pi read and
# work with your Gmail, Drive, Sheets, Docs, Calendar and more, as YOU.
# Per-operator OAuth: no shared keys, the token stays on this machine
# (mode 600). Revoke any time: Google Account > Security > Third-party access,
# then delete ~/.agent_credentials/google-user-token.json (gws auth logout).
#
# Run it like this (it needs your terminal):
#   sh -c "$(curl -fsSL https://onboarding.fornace.app/google-auth.sh)"
set -eu

BASE="https://onboarding.fornace.app"
GWS="$HOME/.pi/agent/skills/google-workspace/scripts/gws.mjs"
TOKEN_FILE="$HOME/.agent_credentials/google-user-token.json"

say() { printf '==> %s\n' "$*"; }
sub() { printf '    %s\n' "$*"; }

if [ ! -t 0 ]; then
  say "This script needs your terminal (it opens a browser consent)."
  sub "Run it like this:"
  sub "sh -c \"\$(curl -fsSL $BASE/google-auth.sh)\""
  exit 1
fi
if ! command -v node >/dev/null 2>&1; then
  say "Node.js is required but not installed."
  sub "Run the bootstrap first:"
  sub "sh -c \"\$(curl -fsSL $BASE/bootstrap.sh)\""
  exit 1
fi
if [ ! -f "$GWS" ]; then
  say "The google-workspace skill is not installed yet."
  sub "Run the Fornace setup first (it installs the skills):"
  sub "sh -c \"\$(curl -fsSL $BASE/setup.sh)\""
  exit 1
fi

if [ -f "$TOKEN_FILE" ]; then
  say "Google already authorized for this machine:"
  node "$GWS" auth status
  sub "To re-authorize or switch account: gws auth logout, then this script again."
  exit 0
fi

say "Google authorization, one browser consent."
sub "Sign in with YOUR fornacestudio.com account, click Allow, come back."
node "$GWS" auth login

echo ""
if [ -f "$TOKEN_FILE" ]; then
  say "Google authorized."
  node "$GWS" auth status
  sub "In pi, ask for example: list my last 3 emails. It uses the google-workspace skill."
  exit 0
else
  say "Authorization not completed."
  sub "Run it again, or in a terminal: node $GWS auth login"
  exit 1
fi
