#!/bin/bash
# Gemini auth login entrypoint: starts display server + noVNC + gemini OAuth.
# Used for server-side OAuth login via browser in Docker.
#
# noVNC serves on port 6080 (proxied by PawFlow to the webchat).
# Gemini has no dedicated `gemini login` subcommand — the first interactive
# launch with `selectedAuthType=oauth-personal` triggers the browser flow.
# After authorization, ~/.gemini/oauth_creds.json is written and copied to
# /workspace.

# Force clean env — Docker Desktop WSL2 injects host PATH/HOME/USER
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
export HOME="/home/pawflow"
export USER="pawflow"
export LANG="C.UTF-8"
export LC_ALL="C.UTF-8"
export TERM="xterm-256color"
unset NO_BROWSER CI GITHUB_ACTIONS
unset GEMINI_API_KEY GOOGLE_API_KEY GOOGLE_GENAI_USE_VERTEXAI
unset GOOGLE_CLOUD_PROJECT GOOGLE_CLOUD_PROJECT_ID GOOGLE_CLOUD_LOCATION
# Work from HOME, not /workspace — gemini reloads its OAuth creds only when
# launched from a directory where the session can resolve ~/.gemini
# (see google-gemini/gemini-cli#5474).
cd "$HOME"

# Pre-create ~/.gemini and seed settings.json so the first launch picks the
# OAuth-personal path immediately (no auth-type selection menu). Newer Gemini
# CLI versions read security.auth.selectedType; keep the legacy root key too so
# older images still work until they are rebuilt.
mkdir -p "$HOME/.gemini"
cat > "$HOME/.gemini/settings.json" 2>/dev/null <<'SETTINGS' || true
{
  "theme": "Default",
  "selectedAuthType": "oauth-personal",
  "security": {
    "auth": {
      "selectedType": "oauth-personal"
    }
  }
}
SETTINGS
# Env fallback for current Gemini CLI auth detection. It maps to the same
# LOGIN_WITH_GOOGLE / oauth-personal path and avoids schema drift in settings.
export GOOGLE_GENAI_USE_GCA="true"

# Start virtual display
Xvfb :99 -screen 0 1280x800x24 -ac &
export DISPLAY=:99

# Wait for display
sleep 0.5

# Start VNC server (no password, shared mode)
x11vnc -display :99 -nopw -forever -shared -rfbport 5900 &

# Start noVNC (WebSocket proxy VNC → port 6080, no idle timeout)
websockify --web /usr/share/novnc --timeout=0 6080 localhost:5900 &

# Wait for services
sleep 1

echo "[gemini-auth-login] Display and noVNC ready on port 6080"

# Chromium flags for Docker (no sandbox for non-root, shared memory)
export CHROME_FLAGS="--no-sandbox --disable-gpu --disable-dev-shm-usage"
export CHROMIUM_FLAGS="$CHROME_FLAGS"
# BROWSER hint so gemini's OAuth opener picks our Chromium wrapper
export BROWSER="/usr/local/bin/open-browser"

# Clear stale credentials
rm -f "$HOME/.gemini/oauth_creds.json" "$HOME/.gemini/google_accounts.json" 2>/dev/null

# Gemini's OAuth bootstrap is TTY-sensitive and also treats NO_BROWSER/CI as
# headless. Build a small inner script and run it directly inside xterm so
# stdin/stdout/stderr stay attached to a real terminal and the browser flow is
# not suppressed.
GEMINI_LOG="/tmp/gemini-auth.log"
: > "$GEMINI_LOG"
cat > /tmp/gemini-login-inner.sh <<'INNER'
#!/bin/bash
set +e
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
export HOME="/home/pawflow"
export USER="pawflow"
export LANG="C.UTF-8"
export LC_ALL="C.UTF-8"
export TERM="xterm-256color"
export DISPLAY=":99"
export BROWSER="/usr/local/bin/open-browser"
unset NO_BROWSER CI GITHUB_ACTIONS
unset GEMINI_API_KEY GOOGLE_API_KEY GOOGLE_GENAI_USE_VERTEXAI
unset GOOGLE_CLOUD_PROJECT GOOGLE_CLOUD_PROJECT_ID GOOGLE_CLOUD_LOCATION
export GOOGLE_GENAI_USE_GCA="true"
mkdir -p "$HOME/.gemini"
cat > "$HOME/.gemini/settings.json" <<'SETTINGS'
{
  "theme": "Default",
  "selectedAuthType": "oauth-personal",
  "security": {
    "auth": {
      "selectedType": "oauth-personal"
    }
  }
}
SETTINGS

echo "Starting Gemini OAuth login..."
echo "TTY check: stdin=$(test -t 0 && echo yes || echo no) stdout=$(test -t 1 && echo yes || echo no) NO_BROWSER=${NO_BROWSER} GEMINI_API_KEY=$(test -n "${GEMINI_API_KEY}" && echo set || echo unset) GOOGLE_GENAI_USE_GCA=${GOOGLE_GENAI_USE_GCA}"
gemini
echo "Gemini process exited. Waiting for PawFlow to read credentials..."
sleep infinity
INNER
chmod +x /tmp/gemini-login-inner.sh
xterm -fa Monospace -fs 14 -bg black -fg white -e /tmp/gemini-login-inner.sh &
GEMINI_PID=$!

# Keep waiting while the browser flow writes credentials. The status endpoint
# polls /workspace/oauth_creds.json, so copy as soon as files appear.
for _ in $(seq 1 300); do
  for f in "$HOME/.gemini/oauth_creds.json" "$HOME/.gemini/google_accounts.json"; do
    if [ -f "$f" ]; then
      echo "[gemini-auth-login] Found: $f"
      cp "$f" "/workspace/$(basename "$f")" 2>/dev/null || true
    fi
  done
  if [ -f "/workspace/oauth_creds.json" ]; then
    break
  fi
  sleep 1
done

kill "$GEMINI_PID" 2>/dev/null || true
wait "$GEMINI_PID" 2>/dev/null || true
ls -la /workspace/oauth_creds.json 2>/dev/null || echo "[gemini-auth-login] WARNING: no oauth_creds.json found"



# Signal completion
touch /tmp/auth_done

# Keep alive until container is killed
echo "[gemini-auth-login] Waiting for server to read credentials..."
sleep infinity
