#!/usr/bin/env bash
# ==============================================================================
# MeetWatch Cross-Platform Extension Installer (Linux)
# Objective: Detect installed Chromium browsers, stage unpacked extension,
# and guide user through Developer Mode installation.
# ==============================================================================

set -euo pipefail

INSTALLER_VERSION="1.0.1"
APP_NAME="MeetWatch"

# ------------------------------------------------------------------------------
# Terminal Colors Setup
# ------------------------------------------------------------------------------
if [ -t 1 ]; then
    C_RESET="\033[0m"
    C_BOLD="\033[1m"
    C_CYAN="\033[96m"
    C_GREEN="\033[92m"
    C_YELLOW="\033[93m"
    C_RED="\033[91m"
    C_MAGENTA="\033[95m"
    C_WHITE="\033[97m"
    C_GRAY="\033[90m"
else
    C_RESET=""
    C_BOLD=""
    C_CYAN=""
    C_GREEN=""
    C_YELLOW=""
    C_RED=""
    C_MAGENTA=""
    C_WHITE=""
    C_GRAY=""
fi

# ------------------------------------------------------------------------------
# Resolve Source and Target Directories
# ------------------------------------------------------------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SOURCE_DIR=""

if [ -f "$SCRIPT_DIR/../extension/manifest.json" ]; then
    SOURCE_DIR="$(cd "$SCRIPT_DIR/../extension" && pwd)"
elif [ -f "$SCRIPT_DIR/../manifest.json" ]; then
    SOURCE_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
elif [ -f "$SCRIPT_DIR/extension/manifest.json" ]; then
    SOURCE_DIR="$(cd "$SCRIPT_DIR/extension" && pwd)"
elif [ -f "$SCRIPT_DIR/manifest.json" ]; then
    SOURCE_DIR="$SCRIPT_DIR"
elif [ -f "./extension/manifest.json" ]; then
    SOURCE_DIR="$(cd "./extension" && pwd)"
fi

DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}"
TARGET_DIR="$DATA_HOME/meetwatch/extension"

# ------------------------------------------------------------------------------
# Show Help
# ------------------------------------------------------------------------------
show_help() {
    cat <<EOF
==============================================================
$APP_NAME Extension Installer v$INSTALLER_VERSION (Linux)
==============================================================
Usage:
  meetwatch-installer.sh [OPTION]

Options:
  --help, -h           Show this help message and exit.
  --update, -u         Check and install latest updates from meetwatch.space.
  --check-browsers     Detect installed browsers and print list.
  --uninstall          Remove staged MeetWatch extension files.
  --test-dry-run       Validate directories and detection without copying.
  --verify-integrity   Verify package files against SHA-256 checksums.

If run without options, launches interactive installation menu.
EOF
    exit 0
}

# ------------------------------------------------------------------------------
# Validate Source Extension Files
# ------------------------------------------------------------------------------
validate_source() {
    if [ -z "$SOURCE_DIR" ]; then
        echo "[ERROR] Could not find the MeetWatch extension source directory." >&2
        echo "Please make sure the 'extension' folder with 'manifest.json' exists." >&2
        exit 1
    fi
    if [ ! -f "$SOURCE_DIR/manifest.json" ]; then
        echo "[ERROR] 'manifest.json' is missing from: $SOURCE_DIR" >&2
        exit 1
    fi
}

# ------------------------------------------------------------------------------
# Browser Detection and Deduplication
# ------------------------------------------------------------------------------
BROWSER_NAMES=()
BROWSER_EXES=()
BROWSER_URLS=()

find_browser() {
    local display_name="$1"
    local ext_url="$2"
    shift 2
    local candidate_bins=("$@")

    for bin in "${candidate_bins[@]}"; do
        if command -v "$bin" >/dev/null 2>&1; then
            local resolved_bin
            resolved_bin="$(command -v "$bin")"
            if [ -x "$resolved_bin" ]; then
                # Avoid duplicate entries of the same browser category
                for existing_name in "${BROWSER_NAMES[@]:-}"; do
                    if [ "$existing_name" = "$display_name" ]; then
                        return 0
                    fi
                done
                BROWSER_NAMES+=("$display_name")
                BROWSER_EXES+=("$resolved_bin")
                BROWSER_URLS+=("$ext_url")
                return 0
            fi
        fi
    done
}

detect_browsers() {
    BROWSER_NAMES=()
    BROWSER_EXES=()
    BROWSER_URLS=()

    # 1. Google Chrome / Chromium
    find_browser "Google Chrome" "chrome://extensions" \
        "google-chrome" "google-chrome-stable" "chromium-browser" "chromium"

    # 2. Microsoft Edge
    find_browser "Microsoft Edge" "edge://extensions" \
        "microsoft-edge" "microsoft-edge-stable" "microsoft-edge-beta" "microsoft-edge-dev"

    # 3. Brave Browser
    find_browser "Brave Browser" "brave://extensions" \
        "brave-browser" "brave-browser-stable" "brave"

    # 4. Opera
    find_browser "Opera" "opera://extensions" \
        "opera" "opera-stable"
}

# ------------------------------------------------------------------------------
# CLI: Check Browsers
# ------------------------------------------------------------------------------
cli_check_browsers() {
    detect_browsers
    echo "=============================================================="
    echo "$APP_NAME - Detected Browsers Check"
    echo "=============================================================="
    local count="${#BROWSER_NAMES[@]}"
    if [ "$count" -eq 0 ]; then
        echo "No supported Chromium browsers detected."
    else
        echo "Detected $count supported browser(s):"
        for i in "${!BROWSER_NAMES[@]}"; do
            local idx=$((i + 1))
            echo "  [$idx] ${BROWSER_NAMES[$i]} - Path: ${BROWSER_EXES[$i]}"
        done
    fi
    exit 0
}

# ------------------------------------------------------------------------------
# CLI: Dry Run
# ------------------------------------------------------------------------------
cli_test_dry_run() {
    validate_source
    detect_browsers
    echo "=============================================================="
    echo "MeetWatch Installer - Dry Run Mode"
    echo "=============================================================="
    echo "Source extension directory: $SOURCE_DIR"
    echo "Target extension directory: $TARGET_DIR"
    echo "Detected browsers: ${#BROWSER_NAMES[@]}"
    for i in "${!BROWSER_NAMES[@]}"; do
        local idx=$((i + 1))
        echo "  [$idx] ${BROWSER_NAMES[$i]} - URL: ${BROWSER_URLS[$i]}"
    done
    echo "Dry run complete. No files were modified."
    exit 0
}

# ------------------------------------------------------------------------------
# Subroutine: Verify Checksums
# ------------------------------------------------------------------------------
verify_integrity() {
    local checksum_file=""
    if [ -f "$SCRIPT_DIR/checksums.sha256" ]; then
        checksum_file="$SCRIPT_DIR/checksums.sha256"
    elif [ -f "$SOURCE_DIR/checksums.sha256" ]; then
        checksum_file="$SOURCE_DIR/checksums.sha256"
    elif [ -f "$SCRIPT_DIR/../checksums.sha256" ]; then
        checksum_file="$SCRIPT_DIR/../checksums.sha256"
    fi

    if [ -z "$checksum_file" ]; then
        echo -e "${C_YELLOW}[INFO]${C_RESET} Checksum manifest checksums.sha256 not found. Skipping file hash verification."
        return 0
    fi

    echo -e "${C_CYAN}[INTEGRITY]${C_RESET} Verifying extension package SHA-256 checksums..."
    local integrity_fail=0

    while read -r expected_hash rel_file || [ -n "$expected_hash" ]; do
        [ -z "$expected_hash" ] && continue
        [[ "$expected_hash" =~ ^# ]] && continue

        # Strip carriage return and leading symbols
        expected_hash="$(echo "$expected_hash" | tr -d '\r')"
        rel_file="$(echo "$rel_file" | tr -d '\r')"
        rel_file="${rel_file#\*}"
        rel_file="${rel_file#./}"

        local check_path=""
        if [ -f "$SOURCE_DIR/$rel_file" ]; then
            check_path="$SOURCE_DIR/$rel_file"
        elif [ -f "$SCRIPT_DIR/$rel_file" ]; then
            check_path="$SCRIPT_DIR/$rel_file"
        elif [ -f "$SCRIPT_DIR/../$rel_file" ]; then
            check_path="$SCRIPT_DIR/../$rel_file"
        fi

        if [ -n "$check_path" ]; then
            local calc_hash=""
            if command -v sha256sum >/dev/null 2>&1; then
                calc_hash=$(sha256sum "$check_path" | awk '{print $1}')
            elif command -v shasum >/dev/null 2>&1; then
                calc_hash=$(shasum -a 256 "$check_path" | awk '{print $1}')
            fi

            if [ "$calc_hash" != "$expected_hash" ]; then
                echo -e "${C_RED}[SECURITY ALERT]${C_RESET} Checksum mismatch for $rel_file"
                echo "  Expected: $expected_hash"
                echo "  Computed: $calc_hash"
                integrity_fail=1
            else
                echo -e "${C_GREEN}[OK]${C_RESET} Verified $rel_file"
            fi
        fi
    done < "$checksum_file"

    if [ "$integrity_fail" -eq 1 ]; then
        echo -e "${C_RED}[ERROR]${C_RESET} Package integrity verification failed! Possible file corruption or tampering." >&2
        return 1
    fi

    echo -e "${C_GREEN}[INTEGRITY]${C_RESET} All package files verified successfully against SHA-256 checksums."
    return 0
}

cli_verify_integrity() {
    validate_source
    verify_integrity
}

# ------------------------------------------------------------------------------
# CLI: Uninstall
# ------------------------------------------------------------------------------
cli_uninstall() {
    echo "=============================================================="
    echo "$APP_NAME Extension Cleanup / Uninstall"
    echo "=============================================================="
    if [ ! -d "$TARGET_DIR" ]; then
        echo "Staged extension directory does not exist: $TARGET_DIR"
        echo "Nothing to remove."
        exit 0
    fi

    echo "This will remove staged extension files from:"
    echo "  $TARGET_DIR"
    echo ""
    read -r -p "Are you sure you want to proceed? [y/N]: " confirm || true
    case "$confirm" in
        [yY]|[yY][eE][sS])
            rm -rf "$TARGET_DIR"
            echo "[SUCCESS] Extension directory removed successfully."
            echo "Remember to remove MeetWatch from your browser's extension list manually."
            ;;
        *)
            echo "Uninstall cancelled by user."
            ;;
    esac
    exit 0
}

# ------------------------------------------------------------------------------
# CLI: Check and Install Updates
# ------------------------------------------------------------------------------
cli_update() {
    echo ""
    echo -e "${C_BOLD}${C_CYAN}==============================================================${C_RESET}"
    echo -e "${C_BOLD}${C_WHITE}           MeetWatch Extension Updater (meetwatch.space)       ${C_RESET}"
    echo -e "${C_BOLD}${C_CYAN}==============================================================${C_RESET}"
    echo ""

    local installed_ver="Unknown"
    if [ -f "$TARGET_DIR/manifest.json" ]; then
        installed_ver=$(grep -i '"version"' "$TARGET_DIR/manifest.json" | head -n1 | sed -E 's/.*"version"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/')
    fi

    echo -e "${C_WHITE}Installed Version:${C_RESET} ${C_CYAN}v${installed_ver}${C_RESET}"
    echo -e "${C_WHITE}Target Directory: ${C_RESET} ${C_GRAY}${TARGET_DIR}${C_RESET}"
    echo ""
    echo -e "${C_CYAN}[→] Querying latest version from https://meetwatch.space/api/version...${C_RESET}"

    local remote_json=""
    if command -v curl >/dev/null 2>&1; then
        remote_json=$(curl -sSL --max-time 10 "https://meetwatch.space/api/version" 2>/dev/null || true)
    elif command -v wget >/dev/null 2>&1; then
        remote_json=$(wget -qO- --timeout=10 "https://meetwatch.space/api/version" 2>/dev/null || true)
    fi

    local remote_ver=$(echo "$remote_json" | grep -o '"version"[[:space:]]*:[[:space:]]*"[^"]*"' | head -n1 | cut -d'"' -f4)

    if [ -z "$remote_ver" ]; then
        echo -e "${C_RED}[ERROR] Could not connect to update server at https://meetwatch.space${C_RESET}" >&2
        exit 1
    fi

    echo -e "${C_WHITE}Latest Server Version:${C_RESET} ${C_BOLD}${C_GREEN}v${remote_ver}${C_RESET}"
    echo ""
    echo -e "${C_CYAN}[→] Downloading latest package: https://meetwatch.space/meetwatch-extension.zip...${C_RESET}"

    local temp_zip="/tmp/meetwatch-update-$$.zip"
    local temp_dir="/tmp/meetwatch-extract-$$"

    if command -v curl >/dev/null 2>&1; then
        curl -sSL "https://meetwatch.space/meetwatch-extension.zip" -o "$temp_zip"
    else
        wget -q "https://meetwatch.space/meetwatch-extension.zip" -O "$temp_zip"
    fi

    if [ ! -f "$temp_zip" ]; then
        echo -e "${C_RED}[ERROR] Failed to download update package.${C_RESET}" >&2
        exit 1
    fi

    echo -e "${C_GREEN}[✓] Download complete.${C_RESET}"
    echo -e "${C_CYAN}[→] Staging new files into ${TARGET_DIR}...${C_RESET}"

    mkdir -p "$TARGET_DIR" "$temp_dir"
    unzip -q -o "$temp_zip" -d "$temp_dir"

    local src_dir="$temp_dir"
    if [ -f "$temp_dir/extension/manifest.json" ]; then
        src_dir="$temp_dir/extension"
    fi

    cp -rf "$src_dir"/* "$TARGET_DIR/"
    rm -rf "$temp_zip" "$temp_dir"

    if [ ! -f "$TARGET_DIR/manifest.json" ]; then
        echo -e "${C_RED}[ERROR] Extraction failed. Please verify permissions.${C_RESET}" >&2
        exit 1
    fi

    echo ""
    echo -e "${C_BOLD}${C_GREEN}==============================================================${C_RESET}"
    echo -e "${C_BOLD}${C_GREEN}[✓] MeetWatch Extension updated successfully to v${remote_ver}!${C_RESET}"
    echo -e "${C_BOLD}${C_GREEN}==============================================================${C_RESET}"
    echo "Location: \"$TARGET_DIR\""
    echo ""
    echo -e "${C_BOLD}${C_YELLOW}Final Step in Your Browser:${C_RESET}"
    echo "1. In your browser (Chrome/Edge/Brave/Opera), go to extensions page."
    echo "2. Click the circular Reload button on the MeetWatch extension card."
    echo ""
    exit 0
}

# ------------------------------------------------------------------------------
# Interactive Main Menu
# ------------------------------------------------------------------------------
main_menu() {
    echo ""
    echo -e "${C_BOLD}${C_CYAN}==============================================================${C_RESET}"
    echo -e "${C_BOLD}${C_WHITE}               MeetWatch Extension Installer${C_RESET}"
    echo -e "${C_BOLD}${C_CYAN}==============================================================${C_RESET}"
    echo ""
    echo -e "${C_BOLD}${C_YELLOW}Privacy & Security Disclosure:${C_RESET}"
    echo -e "${C_GRAY}MeetWatch monitors browser activity only during authorized learning"
    echo -e "sessions (e.g., Google Meet, Zoom, and Google Forms)."
    echo -e "It NEVER collects passwords, cookies, auth tokens, or browsing history"
    echo -e "outside active sessions.${C_RESET}"
    echo ""
    echo -e "${C_CYAN}--------------------------------------------------------------${C_RESET}"

    local consent=""
    read -r -p "$(echo -e "${C_BOLD}${C_WHITE}Do you consent to prepare and install MeetWatch? [${C_BOLD}${C_GREEN}y${C_WHITE}/${C_BOLD}${C_RED}N${C_WHITE}]: ${C_RESET}")" consent || true
    case "$consent" in
        [yY]|[yY][eE][sS]) ;;
        *)
            echo ""
            echo -e "${C_YELLOW}Installation cancelled. No files or browser settings were changed.${C_RESET}"
            exit 0
            ;;
    esac

    validate_source
    detect_browsers

    local count="${#BROWSER_NAMES[@]}"
    if [ "$count" -eq 0 ]; then
        echo ""
        echo -e "${C_BOLD}${C_YELLOW}[NOTICE]${C_RESET} ${C_WHITE}No supported Chromium browser was detected on this computer.${C_RESET}"
        echo "MeetWatch requires a Chromium-based browser:"
        echo -e "  - ${C_CYAN}Google Chrome${C_RESET}   (https://www.google.com/chrome)"
        echo -e "  - ${C_CYAN}Microsoft Edge${C_RESET}  (https://www.microsoft.com/edge)"
        echo -e "  - ${C_CYAN}Brave Browser${C_RESET}   (https://brave.com)"
        echo -e "  - ${C_CYAN}Opera${C_RESET}           (https://www.opera.com)"
        echo ""
        echo "Please install one of the supported browsers and run this installer again."
        exit 0
    fi

    local exit_option=$((count + 1))
    local choice=""

    while true; do
        echo ""
        echo -e "${C_BOLD}${C_CYAN}==============================================================${C_RESET}"
        echo -e "${C_BOLD}${C_WHITE}Detected browsers:${C_RESET}"
        echo ""
        for i in "${!BROWSER_NAMES[@]}"; do
            local idx=$((i + 1))
            echo -e "  ${C_BOLD}${C_CYAN}[$idx]${C_RESET} ${C_BOLD}${C_WHITE}${BROWSER_NAMES[$i]}${C_RESET}"
        done
        echo ""
        echo -e "  ${C_BOLD}${C_YELLOW}[U]${C_RESET} ${C_BOLD}${C_WHITE}Check and Install Updates from meetwatch.space${C_RESET}"
        echo -e "  ${C_BOLD}${C_GRAY}[$exit_option] Exit${C_RESET}"
        echo -e "${C_BOLD}${C_CYAN}==============================================================${C_RESET}"
        read -r -p "$(echo -e "${C_BOLD}${C_YELLOW}Select an option [1-$exit_option or U]: ${C_RESET}")" choice || true

        if [ "$choice" = "u" ] || [ "$choice" = "U" ]; then
            cli_update
        fi

        if [ -z "$choice" ]; then
            echo -e "${C_RED}[ERROR] Please enter a valid number.${C_RESET}"
            continue
        fi

        # Check if numeric
        if ! [[ "$choice" =~ ^[0-9]+$ ]]; then
            echo -e "${C_RED}[ERROR] Invalid input. Please enter numbers or U only.${C_RESET}"
            continue
        fi

        if [ "$choice" -eq "$exit_option" ]; then
            echo -e "${C_YELLOW}Installation cancelled by user.${C_RESET}"
            exit 0
        fi

        if [ "$choice" -lt 1 ] || [ "$choice" -gt "$count" ]; then
            echo -e "${C_RED}[ERROR] Option out of range.${C_RESET}"
            continue
        fi

        break
    done

    local selected_idx=$((choice - 1))
    local selected_name="${BROWSER_NAMES[$selected_idx]}"
    local selected_exe="${BROWSER_EXES[$selected_idx]}"
    local selected_url="${BROWSER_URLS[$selected_idx]}"

    echo ""
    echo -e "${C_GREEN}[✓] Selected:${C_RESET} ${C_BOLD}${C_WHITE}$selected_name${C_RESET}"
    echo -e "${C_GRAY}Browser Path: $selected_exe${C_RESET}"

    # --------------------------------------------------------------------------
    # Stage Extension Files
    # --------------------------------------------------------------------------
    verify_integrity || exit 1

    echo ""
    echo -e "${C_CYAN}Staging extension files...${C_RESET}"
    if [ -d "$TARGET_DIR" ]; then
        echo -e "${C_YELLOW}An existing MeetWatch installation was detected at:${C_RESET}"
        echo "  $TARGET_DIR"
        read -r -p "$(echo -e "Do you want to overwrite it with updated files? [${C_GREEN}Y${C_RESET}/n]: ")" overwrite || true
        case "$overwrite" in
            [nN]|[nN][oO])
                echo -e "${C_GRAY}Keeping existing extension files.${C_RESET}"
                ;;
            *)
                rm -rf "$TARGET_DIR"
                mkdir -p "$TARGET_DIR"
                cp -r "$SOURCE_DIR"/* "$TARGET_DIR"/
                chmod -R u+rwX,go+rX "$TARGET_DIR"
                ;;
        esac
    else
        mkdir -p "$TARGET_DIR"
        cp -r "$SOURCE_DIR"/* "$TARGET_DIR"/
        chmod -R u+rwX,go+rX "$TARGET_DIR"
    fi

    if [ ! -f "$TARGET_DIR/manifest.json" ]; then
        echo -e "${C_RED}[ERROR] Failed to stage extension files to $TARGET_DIR.${C_RESET}" >&2
        exit 1
    fi

    echo -e "${C_BOLD}${C_GREEN}[✓] Extension files ready at:${C_RESET} $TARGET_DIR"

    # --------------------------------------------------------------------------
    # Launch Browser & Instructions
    # --------------------------------------------------------------------------
    echo ""
    # Copy target directory to clipboard if tool is available
    if command -v wl-copy >/dev/null 2>&1; then
        printf "%s" "$TARGET_DIR" | wl-copy
        echo -e "${C_BOLD}${C_GREEN}[✓] Extension directory path copied to clipboard!${C_RESET}"
    elif command -v xclip >/dev/null 2>&1; then
        printf "%s" "$TARGET_DIR" | xclip -selection clipboard
        echo -e "${C_BOLD}${C_GREEN}[✓] Extension directory path copied to clipboard!${C_RESET}"
    fi

    echo -e "${C_CYAN}[→] Launching $selected_name directly to ${C_BOLD}$selected_url${C_RESET}..."
    if ! "$selected_exe" "$selected_url" >/dev/null 2>&1 & then
        echo -e "${C_YELLOW}[WARNING] Could not automatically open $selected_name.${C_RESET}"
        echo -e "Please open your browser manually and navigate to: ${C_CYAN}$selected_url${C_RESET}"
    fi

    echo ""
    echo -e "${C_BOLD}${C_CYAN}==============================================================${C_RESET}"
    echo -e "${C_BOLD}${C_WHITE}             Final 2 Steps in Your Browser Window             ${C_RESET}"
    echo -e "${C_BOLD}${C_CYAN}==============================================================${C_RESET}"
    echo -e "${C_WHITE}Browser page opened: ${C_BOLD}${C_CYAN}$selected_url${C_RESET}"
    echo -e "${C_WHITE}Folder path: ${C_BOLD}${C_GREEN}$TARGET_DIR${C_RESET}"
    echo ""
    echo -e "${C_BOLD}${C_YELLOW}  1. Turn ON the ${C_BOLD}${C_WHITE}\"Developer mode\"${C_RESET}${C_BOLD}${C_YELLOW} toggle switch (top-right corner).${C_RESET}"
    echo ""
    echo -e "${C_BOLD}${C_YELLOW}  2. Click the ${C_BOLD}${C_CYAN}\"Load unpacked\"${C_RESET}${C_BOLD}${C_YELLOW} button (top-left toolbar).${C_RESET}"
    echo ""
    echo -e "${C_BOLD}${C_YELLOW}  3. In the folder picker dialog that opens, select or paste:${C_RESET}"
    echo -e "     ${C_BOLD}${C_GREEN}$TARGET_DIR${C_RESET}"
    echo ""
    echo -e "${C_CYAN}--------------------------------------------------------------${C_RESET}"
    echo -e "${C_BOLD}${C_CYAN}Installation Verification Checklist:${C_RESET}"
    echo -e "  ${C_BOLD}${C_GREEN}[✓]${C_RESET} \"MeetWatch\" appears in your browser's extensions list."
    echo -e "  ${C_BOLD}${C_GREEN}[✓]${C_RESET} The toggle switch for MeetWatch is turned ${C_BOLD}${C_GREEN}ON${C_RESET}."
    echo -e "  ${C_BOLD}${C_GREEN}[✓]${C_RESET} The MeetWatch icon appears in your toolbar or extensions menu."
    echo -e "  ${C_BOLD}${C_GREEN}[✓]${C_RESET} Clicking the MeetWatch icon opens the extension popup window."
    echo -e "  ${C_BOLD}${C_GREEN}[✓]${C_RESET} There are no red \"Errors\" buttons on the MeetWatch extension card."
    echo -e "${C_BOLD}${C_CYAN}==============================================================${C_RESET}"
    echo -e "${C_GRAY}NOTE: Browser security policies prevent scripts from silently
loading unpacked extensions without your manual confirmation.${C_RESET}"
    echo -e "${C_BOLD}${C_CYAN}==============================================================${C_RESET}"
    exit 0
}

# ------------------------------------------------------------------------------
# Entrypoint Dispatcher
# ------------------------------------------------------------------------------
case "${1:-}" in
    --help|-h|-\?)
        show_help
        ;;
    --update|-u)
        cli_update
        ;;
    --check-browsers)
        cli_check_browsers
        ;;
    --test-dry-run)
        cli_test_dry_run
        ;;
    --verify-integrity)
        cli_verify_integrity
        ;;
    --uninstall)
        cli_uninstall
        ;;
    *)
        main_menu
        ;;
esac
