#!/usr/bin/env bash
# Gemini CLI — Uninstaller
# Removes Gemini CLI, settings, env vars, and npm registry config.
#
# Usage: sudo bash ugemini_uninstall.sh
set -euo pipefail

GREEN="\033[92m"
RED="\033[91m"
CYAN="\033[96m"
YELLOW="\033[93m"
BOLD="\033[1m"
RESET="\033[0m"

log()  { echo -e "${GREEN}[+]${RESET} $*"; }
warn() { echo -e "${YELLOW}[~]${RESET} $*"; }
info() { echo -e "${CYAN}[i]${RESET} $*"; }

echo -e "${BOLD}"
echo "  +--------------------------------------+"
echo "  |    Gemini CLI — Uninstaller          |"
echo "  +--------------------------------------+"
echo -e "${RESET}"

# ---- Uninstall npm package ----

if command -v gemini &>/dev/null || npm list -g @google/gemini-cli &>/dev/null 2>&1; then
    info "Removing @google/gemini-cli..."
    npm uninstall -g @google/gemini-cli 2>/dev/null || true
    log "npm package removed"
else
    warn "Gemini CLI not found in npm global packages"
fi

# ---- Remove settings ----

for user_home in /root /home/*; do
    GEMINI_DIR="$user_home/.gemini"
    if [ -d "$GEMINI_DIR" ]; then
        info "Removing $GEMINI_DIR..."
        rm -rf "$GEMINI_DIR"
        log "Removed $GEMINI_DIR"
    fi
done

# ---- Remove env vars from shell rc files ----

for user_home in /root /home/*; do
    for rc_file in "$user_home/.bashrc" "$user_home/.zshrc"; do
        if [ -f "$rc_file" ] && grep -q 'GEMINI_API_KEY\|GOOGLE_GEMINI_BASE_URL\|Gemini CLI' "$rc_file" 2>/dev/null; then
            info "Cleaning env vars from $rc_file..."
            sed -i '/# Gemini CLI/d' "$rc_file"
            sed -i '/GEMINI_API_KEY/d' "$rc_file"
            sed -i '/GOOGLE_GEMINI_BASE_URL/d' "$rc_file"
            log "Cleaned $rc_file"
        fi
    done
done

# ---- Remove /etc/profile.d script ----

if [ -f "/etc/profile.d/gemini-cli.sh" ]; then
    info "Removing /etc/profile.d/gemini-cli.sh..."
    rm -f "/etc/profile.d/gemini-cli.sh"
    log "Removed /etc/profile.d/gemini-cli.sh"
fi

# ---- Remove env vars from /etc/environment ----

if [ -f "/etc/environment" ] && grep -q 'GEMINI_API_KEY\|GOOGLE_GEMINI_BASE_URL' /etc/environment 2>/dev/null; then
    info "Cleaning /etc/environment..."
    sed -i '/GEMINI_API_KEY/d' /etc/environment
    sed -i '/GOOGLE_GEMINI_BASE_URL/d' /etc/environment
    log "Cleaned /etc/environment"
fi

# ---- Remove npm registry config ----

info "Removing npm registry config..."
npm config delete @google:registry 2>/dev/null || true
log "npm registry config removed"

echo ""
echo -e "${GREEN}${BOLD}  Gemini CLI fully uninstalled!${RESET}"
echo ""
