#!/bin/bash

# bin/better-anonymity
# Main CLI entrypoint

# Resolve absolute path to the project root
# Handle symlinks to ensure we find the real lib/ directory
SOURCE="${BASH_SOURCE[0]}"
# Resolve path reliably (Python fallback for macOS/Linux)
# 1. If SOURCE is just a command name (not a path) or relative and not found, resolve via PATH
if [[ "$SOURCE" != */* ]] && [ ! -f "$SOURCE" ] && [ ! -L "$SOURCE" ]; then
    CMD_SOURCE=$(command -v "$SOURCE")
    if [ -n "$CMD_SOURCE" ]; then
        SOURCE="$CMD_SOURCE"
    fi
fi

RESOLVED_SOURCE=""

# 2. Try Python (Most robust, handles symlinks recursively)
if [ -z "$RESOLVED_SOURCE" ] && command -v python3 >/dev/null 2>&1; then
    # Redirect stderr to devnull to avoid permission errors
    RESOLVED_SOURCE=$(python3 -c "import os; print(os.path.realpath('${BASH_SOURCE[0]}'))" 2>/dev/null)
fi

# 3. Try Perl (Native on macOS/Linux fallback)
if [ -z "$RESOLVED_SOURCE" ] && command -v perl >/dev/null 2>&1; then
    RESOLVED_SOURCE=$(perl -MCwd -e 'print Cwd::abs_path(shift)' "$SOURCE" 2>/dev/null)
fi

if [ -n "$RESOLVED_SOURCE" ]; then
    SOURCE="$RESOLVED_SOURCE"
    DIR="$(dirname "$SOURCE")"
else
    # 4. Fallback shell loop (Last resort)
    while [ -h "$SOURCE" ]; do 
        DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
        SOURCE="$(readlink "$SOURCE")"
        [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" 
    done
    DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
fi

# Resolve paths
SCRIPT_PATH=$(realpath "$0")
# If invoked through a symlink (like Homebrew), resolve to actual file
while [ -h "$SCRIPT_PATH" ]; do
  SCRIPT_PATH=$(readlink "$SCRIPT_PATH")
done
BIN_DIR=$(dirname "$SCRIPT_PATH")
ROOT_DIR=$(dirname "$BIN_DIR")

# Export for use in subprocesses
export ROOT_DIR

# Determine installation type and set paths accordingly
# 1. Pip installation: lib/better-anonymity structure
# 2. Homebrew: symlink in /usr/local or /opt/homebrew
# 3. Source: standard project structure
if [ -d "$ROOT_DIR/lib/better-anonymity" ]; then
    # Pip installation
    LIB_DIR="$ROOT_DIR/lib/better-anonymity"
    CONFIG_DIR="$ROOT_DIR/config/better-anonymity"
    INSTALL_TYPE="pip"
else
    # Source or Homebrew installation (both use standard structure)
    LIB_DIR="$ROOT_DIR/lib"
    CONFIG_DIR="$ROOT_DIR/config"
    # Detect if it's Homebrew by checking the path
    if [[ "$SCRIPT_PATH" == *"/Cellar/"* ]] || [[ "$SCRIPT_PATH" == *"/opt/homebrew/"* ]]; then
        INSTALL_TYPE="homebrew"
    else
        INSTALL_TYPE="source"
    fi
fi

# Export for use in subprocesses
export LIB_DIR CONFIG_DIR

# Check if lib exists
if [ ! -d "$LIB_DIR" ]; then
    echo "Error: Library directory not found at $LIB_DIR"
    echo "Installation type: $INSTALL_TYPE"
    echo "Script path: $SCRIPT_PATH"
    exit 1
fi

# Source Core Libraries (Essential)
source "$LIB_DIR/core.sh"
source "$LIB_DIR/platform.sh"

# Initialize capabilities
detect_arch
detect_os_version
detect_model
check_macos
detect_wifi_network
detect_active_network

usage() {
    if [ -f "$LIB_DIR/banner.txt" ]; then
        cat "$LIB_DIR/banner.txt"
    fi
     # Indent aggressively to bypass CI terminal truncation (consumes ~9 chars)
    echo "         Usage: better-anonymity [command] [options]"
    echo ""
    echo "Core Commands:"
    echo "  menu              Interactive menu (default)"
    echo "  setup             Run first-time setup wizard"
    echo "  auto              Run comprehensive setup automatically (Non-interactive)"
    echo "  daily             Run daily health checks"
    echo "  update            Update better-anonymity (git pull)"
    echo "  help              Show this help"
    echo ""
    echo "Security & Privacy:"
    echo "  harden            Run macOS hardening checks"
    echo "  harden browser    Inject the offline aggressive better-anonymity user.js into active profiles"
    echo "  misc-harden       Run miscellaneous hardening (Finder, sudoers, etc.)"
    echo "  verify-security   Verify system security status"
    echo "  cleanup           Run system and browser cleanup"
    echo "  generate-password Generate a secure passphrase"
    echo ""
    echo "Network & Connectivity:"
    echo "  dns [provider]    Set DNS (dnscrypt-proxy, quad9, mullvad, cloudflare, system default)"
    echo "  verify-dns        Verify DNS configuration"
    echo "  update-hosts      Update StevenBlack hosts blocklist"
    echo "  wifi [cmd]        Wi-Fi tools (audit, spoof-mac, daemon-on, daemon-off)"
    echo "  ssh [cmd]         SSH tools (audit-sshd, harden-client)"
    echo "  network-open      Restore network defaults (disable proxy, resetting services)"
    echo "  network-anon      Enable anonymity mode (starts DNSCrypt, Privoxy, Tor, I2P; sets System/SOCKS proxies)"
    echo "  firewall [cmd]    Manage hardware IP firewall (blocklist, unblock)"
    echo ""
    echo "Tools & Services:"
    echo "  install [tool]    Install tools (tor, i2p, privoxy, gpg, signal, linkliar, etc.)"
    echo "  tor [cmd]         Manage Tor service (start, stop, restart, new-id, proxy-on/off, status)"
    echo "  captive [cmd]     Manage captive portal monitor (monitor, run, status)"
    echo "  i2p [cmd]         Manage I2P service (start, stop, console)"
    echo "  vault [cmd]       Manage password vault (read, write)"
    echo "  backup [cmd]      Secure backup tools (encrypt, decrypt)"
    echo "  diagnose          Run system diagnosis"
    echo ""
    echo "CLI Management:"
    echo "  install           Install global CLI aliases"
    echo "  uninstall         Remove global CLI aliases"
    echo "  test              Run unit tests"
    echo "  --version         Show version information"
    echo ""
    echo "Convenience Aliases (Available after 'install'):"
    echo "  torify            Enable Tor proxy (export ALL_PROXY=socks5h://...)"
    echo "  untorify          Disable Tor proxy (unset ALL_PROXY)"
    echo "  tor-run [cmd]     Run single command through Tor (tor-run curl ...)"
    echo "  stay-connected    Launch Captive Portal Monitor (alias to 'captive monitor')"
    echo "  i2pify            Enable I2P HTTP proxy (export http_proxy=...)"
    echo ""
}

get_version() {
    if [ -f "$ROOT_DIR/VERSION" ]; then
        cat "$ROOT_DIR/VERSION"
    else
        echo "Unknown"
    fi
}

# Handle global flags
# Scan all arguments for --explain or --auto
EXPLAIN_MODE=0
args=()
for arg in "$@"; do
    if [[ "$arg" == "--explain" ]]; then
        EXPLAIN_MODE=1
    elif [[ "$arg" == "--auto" ]]; then
        export BETTER_ANONYMITY_AUTO_YES=1
    else
        args+=("$arg")
    fi
done
set -- "${args[@]}"

if [[ "$1" == "--version" ]] || [[ "$1" == "-v" ]]; then
    echo "better-anonymity $(get_version)"
    exit 0
fi

show_explanation() {
    local cmd="$1"
    local subcmd="$2"
    
    echo "Explanation for command: '$cmd' ${subcmd:+($subcmd)}"
    echo "---------------------------------------------------"
    
    case "$cmd" in
        menu|"" )
            echo "Launches the interactive menu system."
            echo "Allows navigation through all features via arrow keys."
            ;;
        harden)
            if [ "$subcmd" == "browser" ]; then
                echo "Initiates targeted Browser Hardening payload."
                echo "Searches for Firefox and LibreWolf profiles and injects a static 'user.js' to disable WebRTC, analytics, and fingerprinting."
            else
                echo "Runs the complete macOS hardening suite."
                echo "Applying settings for Firewall, Privacy, Finder, and System preferences."
            fi
            ;;
        dns)
            echo "Configures the system DNS servers."
            echo "Valid providers: dnscrypt-proxy, quad9, mullvad, cloudflare, system default."
            echo "This changes network settings to route DNS queries through the chosen encrypted provider."
            ;;
        install)
            echo "Installs specified privacy tools/services."
            echo "Tools: tor, i2p, privoxy, gpg, signal, telegram, session, firefox, keepassxc, etc."
            echo "This will download binaries/recipes and configure them."
            ;;
        verify-dns)
            echo "Verifies the current DNS configuration."
            echo "Checks for DNS leaks and confirms DNSSEC validation."
            ;;
        verify-security)
            echo "Verifies the system security posture."
            echo "Audit checks for: SIP, FileVault, Firewall, Stealth Mode, etc."
            ;;
        install-firefox-extensions)
            echo "Installs privacy extensions (e.g. uBlock Origin) for Firefox."
            echo "Downloads .xpi files directly to the profile extensions folder."
            ;;
        cleanup|cleanup-metadata)
            echo "Performs system and privacy cleanup to remove tracking metadata."
            echo "Clears: QuickLook cache, browser artifacts, and logs."
            ;;
        network-open)
            echo "Restores standard network connectivity."
            echo "Disables local proxies (Privoxy/DNSCrypt) and resets DNS to system default."
            ;;
        network-anon)
            echo "Enables the Anonymity Network Stack."
            echo "Starts Tor/Privoxy/DNSCrypt and routes traffic through them."
            ;;
        test)
            echo "Runs the internal Unit Test Suite."
            echo "Verifies that all functions of the CLI are working correctly."
            ;;
        setup)
            echo "Runs the First-Time Setup Wizard."
            echo "Interactive guide to apply the security baseline."
            ;;
        auto)
            echo "Runs the First-Time Setup in non-interactive (automatic) mode."
            echo "Applies defaults for all prompts."
            ;;
        daily)
            echo "Runs the Daily Health Check."
            echo "Verifies all security settings and updates blocklists."
            ;;
        captive-monitor) 
            echo "Captive Portal Monitor (Legacy). Use 'captive run' or 'captive monitor'."
            ;;
        captive)
            echo "Captive Portal Management."
            echo "Subcommands: start, stop, status, monitor, run."
            ;;
        tor)
            echo "Tor Service Management."
            echo "Subcommands: start, stop, restart, new-id, status, install."
            ;;
        update)
            echo "Updates the 'better-anonymity' codebase from git."
            ;;
        check-update)
            echo "Checks if a new version is available without installing it."
            ;;
        uninstall)
            echo "Removes the global CLI aliases (b-a, better-anonymity)."
            ;;
        diagnose)
            echo "Runs system diagnostics to identify issues with the environment."
            ;;
        wifi)
            echo "Wi-Fi Privacy Tools."
            echo "Can audit current security, spoof the MAC address, or manage the boot daemon."
            ;;
        firewall)
            echo "Hardware IP Firewall Management."
            echo "Commands: blocklist, unblock."
            echo "Downloads massive Threat Intelligence IP lists and injects them natively into macOS pfctl."
            ;;
        ssh)
            echo "SSH Hardening Tools."
            echo "Can audit sshd config or harden client/server configurations."
            ;;

        i2p)
            echo "I2P Service Management."
            echo "Manage the generic Invisible Internet Project router (start/stop/console)."
            ;;
        vault)
            echo "Secure Password Vault."
            ;;
        backup)
            echo "Encrypted Backup Tools."
            ;;
        misc-harden)
            echo "Runs miscellaneous hardening checks."
            echo "Tweaks Finder, sudoers, umask, and removes Guest account."
            ;;
        generate-password)
            echo "Generates a cryptographically secure passphrase."
            echo "Checks strength against dictionary attacks."
            ;;
        update-hosts)
            echo "Updates the StevenBlack hosts file."
            echo "Used for system-wide ad and tracker blocking."
            ;;
        help|--help|-h)
            echo "Displays the help menu and usage information."
            ;;
        *)
            echo "Command: $cmd"
            echo "Run 'better-anonymity help' for usage details."
            ;;
    esac
    exit 0
}

# Main Command Dispatch
COMMAND="$1"
# Sanitize command: remove non-breaking spaces and trim
# Hex A0 is NBSP. We use tr to remove it if present.
if [[ -n "$COMMAND" ]]; then
    COMMAND=$(echo "$COMMAND" | tr -d '\240' | xargs)
fi
shift

# Handle Explain Mode
if [ "$EXPLAIN_MODE" -eq 1 ]; then
    show_explanation "$COMMAND" "$1"
fi

case "$COMMAND" in
    menu|"" )
        load_module "menus"
        interactive_menu
        ;;
    harden)
        if [[ "$1" == "browser" ]]; then
            load_module "browser_hardening"
            harden_browser_profiles
        else
            load_module "macos_hardening"
            hardening_run_all
        fi
        ;;
    dns)
        if [[ -z "$1" ]]; then
            error "Usage: better-anonymity dns [dnscrypt-proxy|quad9|mullvad|cloudflare|localhost|default]"
            exit 1
        fi
        load_module "network"
        network_set_dns "$1"
        ;;
    install)
        TOOL="$1"
        if [ -z "$TOOL" ]; then
             load_module "lifecycle"
             lifecycle_install_cli
        else
            case "$TOOL" in
                tor) 
                    load_module "tor_manager"
                    tor_install 
                    ;;
                tor-browser)
                    load_module "installers"
                    install_tor_browser
                    ;;
                privoxy) 
                    load_module "installers"
                    install_privoxy 
                    ;;
                gpg) 
                    load_module "installers"
                    install_gpg 
                    ;;
                dnscrypt|dnscrypt-proxy) 
                    load_module "installers"
                    install_dnscrypt 
                    ;;
                pingbar) 
                    load_module "installers"
                    install_pingbar 
                    ;;
                unbound) 
                    load_module "installers"
                    install_unbound 
                    ;;
                firefox)
                    load_module "installers"
                    install_firefox
                    ;;
                firefox-extensions)
                    load_module "installers"
                    install_firefox_extensions
                    ;;
                keepassxc)
                    load_module "installers"
                    install_keepassxc
                    ;;
                signal)
                    load_module "installers"
                    install_signal
                    ;;
                telegram)
                    load_module "installers"
                    install_telegram
                    ;;
                session)
                    load_module "installers"
                    install_session
                    ;;
                linkliar)
                    load_module "installers"
                    install_linkliar
                    ;;
                onionshare)
                    load_module "installers"
                    install_onionshare
                    ;;
                i2p)
                    load_module "i2p_manager"
                    i2p_install
                    ;;
                cli)
                    load_module "lifecycle"
                    lifecycle_install_cli
                    ;;
                *) error "Unknown tool: $TOOL. Available: tor, tor-browser, privoxy, gpg, dnscrypt, pingbar, unbound, firefox, firefox-extensions, keepassxc, signal, telegram, session, linkliar, onionshare, i2p, cli." ;;
            esac
        fi
        ;;
    verify-dns)
        load_module "network"
        network_verify_anonymity
        ;;
    verify-security)
        load_module "macos_hardening"
        hardening_verify
        ;;

    harden-firefox)
         load_module "installers"
         harden_firefox
         ;;

    setup-gpg)
         load_module "installers"
         setup_gpg
         ;;

    cleanup|cleanup-metadata)
         load_module "cleanup"
         cleanup_metadata
         ;;
    firewall)
         load_module "firewall"
         case "$1" in
            blocklist) firewall_enable_blocklist ;;
            unblock)   firewall_disable_blocklist ;;
            *)         error "Usage: better-anonymity firewall [blocklist|unblock]" ;;
         esac
         ;;
    vault)
         load_module "vault"
         case "$1" in
            write|w) 
                if [ -z "$2" ]; then error "Usage: better-anonymity vault write <key_name>"; exit 1; fi
                vault_write "$2" ;;
            read|r)  
                if [ -z "$2" ]; then error "Usage: better-anonymity vault read <key_name>"; exit 1; fi
                vault_read "$2" ;;
            list|l)  vault_list ;;
            *) echo "Usage: better-anonymity vault [write|read|list]" ;;
         esac
         ;;
    backup)
         load_module "backup"
         case "$1" in
            encrypt) 
                if [ -z "$2" ]; then error "Usage: better-anonymity backup encrypt <source_dir> [dest_file]"; exit 1; fi
                backup_encrypt_dir "$2" "$3" ;;
            decrypt) 
                if [ -z "$2" ]; then error "Usage: better-anonymity backup decrypt <file> [dest_file]"; exit 1; fi
                backup_decrypt_dir "$2" "$3" ;;
            volume|create-volume) 
                if [ -z "$2" ] || [ -z "$3" ]; then error "Usage: better-anonymity backup volume <name> <size>"; exit 1; fi
                backup_create_volume "$2" "$3" ;;
            audit|audit-tm) backup_audit_timemachine ;;
            *) echo "Usage: better-anonymity backup [encrypt|decrypt|volume|audit]" ;;
         esac
         ;;
    wifi)
         load_module "wifi"
         case "$1" in
            audit) wifi_audit ;;
            spoof-mac|spoof)
                 mac=$(wifi_generate_mac)
                 wifi_spoof_mac "$mac"
                 ;;
            daemon-on) wifi_install_spoof_daemon ;;
            daemon-off) wifi_uninstall_spoof_daemon ;;
            *) echo "Usage: better-anonymity wifi [audit|spoof-mac|daemon-on|daemon-off]" ;;
         esac
         ;;
    ssh)
         load_module "ssh"
         case "$1" in
            audit-sshd) ssh_check_sshd_status ;;
            harden-sshd) ssh_harden_sshd ;;
            harden-client) ssh_harden_client ;;
            hash-hosts) ssh_hash_hosts ;;
            "") # No argument provided, open menu
               load_module "menus"
               menu_ssh
               ;;
            *) echo "Usage: better-anonymity ssh [audit-sshd|harden-sshd|harden-client|hash-hosts]" ;;
         esac
         ;;

    i2p)
         load_module "i2p_manager"
         case "$1" in
            install) i2p_install ;;
            start)   i2p_start ;;
            stop)    i2p_stop ;;
            restart) i2p_restart ;;
            status)  i2p_status ;;
            console) i2p_console ;;
            info)    i2p_info ;;
            *) 
               echo "Usage: better-anonymity i2p [install|start|stop|restart|status|console|info]" 
               ;;
         esac
         ;;
    misc-harden)
        load_module "macos_hardening"
        hardening_harden_finder
        hardening_disable_bonjour
        hardening_secure_sudoers
        hardening_set_umask
        hardening_disable_analytics
        hardening_remove_guest
        hardening_privacy_tweaks
        hardening_reset_tcc
        ;;
    update-hosts)
        load_module "network"
        network_update_hosts
        ;;
    network-open)
        load_module "network"
        network_restore_default
        ;;
    network-anon)
        load_module "network"
        network_enable_anonymity
        ;;
    test)
        echo "Running Unit Tests..."
        "$ROOT_DIR/tests/unit_logic.sh"
        ;;
    setup)
        load_module "lifecycle"
        lifecycle_setup
        ;;
    auto)
        export BETTER_ANONYMITY_AUTO_YES=1
        load_module "lifecycle"
        lifecycle_setup
        ;;
    daily)
        load_module "lifecycle"
        lifecycle_daily
        ;;
    update)
        load_module "lifecycle"
        lifecycle_update
        ;;
    check-update)
        load_module "lifecycle"
        lifecycle_check_update
        ;;
    uninstall)
        load_module "lifecycle"
        lifecycle_uninstall
        ;;
    diagnose)
        load_module "diagnosis"

        # Diagnosis relies on 'is_brew_installed' (core.sh) and 'check_airport_exists' (core.sh).
        # It also relies on 'networksetup' and platform detection from platform.sh.
        # These are sourced globally at the top of this script, so they are available here.
        diagnosis_run
        ;;
    captive-monitor)
        load_module "captive"
        captive_dispatcher monitor
        ;;
    captive)
        load_module "captive"
        captive_dispatcher "$@"
        ;;
    tor)
        load_module "tor_manager"
        tor_dispatcher "$1"
        ;;
    generate-password)
        load_module "password_utils"
        input_count="${1:-6}"
        pwd=$(generate_password "$input_count")
        info "Generated Password: $pwd"
        check_strength "$pwd"
        ;;
    help|--help|-h)
        usage
        ;;
    *)
        error "Unknown command: $COMMAND"
        usage
        exit 1
        ;;
esac
