#!/usr/bin/env bash
# Codex CLI — Uninstaller
# Removes Codex CLI binary, config, env vars.
#
# Usage: sudo bash ucodex_uninstall.sh
set -euo pipefail

GREEN="\033[92m"
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 "  |    Codex CLI — Uninstaller           |"
echo "  +--------------------------------------+"
echo -e "${RESET}"

# ---- Remove binary ----

CODEX_PATH=$(which codex 2>/dev/null || echo "")
if [ -n "$CODEX_PATH" ]; then
    info "Removing binary: $CODEX_PATH"
    rm -f "$CODEX_PATH"
    log "Binary removed"
else
    warn "Codex binary not found in PATH"
fi

# ---- Remove config ----

for user_home in /root /home/*; do
    CODEX_DIR="$user_home/.codex"
    if [ -d "$CODEX_DIR" ]; then
        info "Removing $CODEX_DIR..."
        rm -rf "$CODEX_DIR"
        log "Removed $CODEX_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 'OPENAI_API_KEY\|OPENAI_BASE_URL\|Codex' "$rc_file" 2>/dev/null; then
            info "Cleaning env vars from $rc_file..."
            sed -i '/# Codex/d' "$rc_file"
            sed -i '/# UnlimitedCoding.*[Cc]odex/d' "$rc_file"
            sed -i '/OPENAI_API_KEY/d' "$rc_file"
            sed -i '/OPENAI_BASE_URL/d' "$rc_file"
            log "Cleaned $rc_file"
        fi
    done
done

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

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

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

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

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