#!/usr/bin/env bash
# ==============================================================================
# Nerd Fonts, Symbols & Emojis Universal Installer
# Installs complete Nerd Fonts (FiraCode Nerd Font, Symbols Nerd Font),
# Google Noto Color Emoji, FontAwesome icons, and Fontconfig fallbacks.
# Compatible with: Debian/Ubuntu/Kali, Arch Linux, Fedora/RHEL, Alpine, and macOS.
# ==============================================================================

set -e

# ANSI Color codes for installer output
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
YELLOW='\033[1;33m'
BOLD='\033[1m'
NC='\033[0m' # No Color

info() { echo -e "${CYAN}[*]${NC} $1"; }
success() { echo -e "${GREEN}[+]${NC} $1"; }
warn() { echo -e "${YELLOW}[!]${NC} $1"; }
error() { echo -e "${RED}[-]${NC} $1"; }

echo -e "${BLUE}${BOLD}"
cat << "BANNER"
  ___________________________________________________________
 /                                                           \
 |       Nerd Fonts, Symbols & Emojis Universal Setup        |
 \___________________________________________________________/
BANNER
echo -e "${NC}"

# Detect execution privileges
IS_ROOT=false
if [ "$EUID" -eq 0 ]; then
    IS_ROOT=true
fi

# Detect package manager
PKG_MGR=""
if command -v apt-get >/dev/null 2>&1; then
    PKG_MGR="apt"
elif command -v pacman >/dev/null 2>&1; then
    PKG_MGR="pacman"
elif command -v dnf >/dev/null 2>&1; then
    PKG_MGR="dnf"
elif command -v zypper >/dev/null 2>&1; then
    PKG_MGR="zypper"
elif command -v apk >/dev/null 2>&1; then
    PKG_MGR="apk"
elif command -v brew >/dev/null 2>&1; then
    PKG_MGR="brew"
fi

# ------------------------------------------------------------------------------
# 1. Install System Dependencies & Native Font Packages
# ------------------------------------------------------------------------------
info "Detected package manager: ${PKG_MGR:-none}"
info "Installing native font packages and extraction utilities (tar, xz, curl)..."

install_packages() {
    case "$PKG_MGR" in
        apt)
            local pkgs=(
                curl tar xz-utils fontconfig
                fonts-firacode
                fonts-font-awesome
                fonts-font-awesome-legacy
                fonts-noto-color-emoji
                fonts-hack
            )
            if [ "$IS_ROOT" = true ]; then
                apt-get update -qq || true
                apt-get install -y "${pkgs[@]}" 2>/dev/null || true
            elif command -v sudo >/dev/null 2>&1; then
                sudo apt-get update -qq || true
                sudo apt-get install -y "${pkgs[@]}" 2>/dev/null || true
            else
                warn "Sudo unavailable; proceeding with user-space font downloads."
            fi
            ;;
        pacman)
            local pkgs=(
                curl tar xz fontconfig
                ttf-fira-code
                ttf-font-awesome
                noto-fonts-emoji
                ttf-nerd-fonts-symbols
            )
            if [ "$IS_ROOT" = true ]; then
                pacman -Sy --noconfirm "${pkgs[@]}" 2>/dev/null || true
            elif command -v sudo >/dev/null 2>&1; then
                sudo pacman -Sy --noconfirm "${pkgs[@]}" 2>/dev/null || true
            fi
            ;;
        dnf)
            local pkgs=(
                curl tar xz fontconfig
                fira-code-fonts
                fontawesome-fonts
                google-noto-color-emoji-fonts
            )
            if [ "$IS_ROOT" = true ]; then
                dnf install -y "${pkgs[@]}" 2>/dev/null || true
            elif command -v sudo >/dev/null 2>&1; then
                sudo dnf install -y "${pkgs[@]}" 2>/dev/null || true
            fi
            ;;
        zypper)
            local pkgs=(curl tar xz fontconfig noto-coloremoji-fonts)
            if [ "$IS_ROOT" = true ]; then
                zypper install -y "${pkgs[@]}" 2>/dev/null || true
            elif command -v sudo >/dev/null 2>&1; then
                sudo zypper install -y "${pkgs[@]}" 2>/dev/null || true
            fi
            ;;
        apk)
            local pkgs=(curl tar xz fontconfig font-noto-emoji)
            if [ "$IS_ROOT" = true ]; then
                apk add --no-cache "${pkgs[@]}" 2>/dev/null || true
            elif command -v sudo >/dev/null 2>&1; then
                sudo apk add --no-cache "${pkgs[@]}" 2>/dev/null || true
            fi
            ;;
        brew)
            brew install fontconfig curl 2>/dev/null || true
            brew install --cask font-fira-code-nerd-font font-symbols-only-nerd-font font-noto-color-emoji 2>/dev/null || true
            ;;
        *)
            warn "Unrecognized package manager. Proceeding with user-space font downloads."
            ;;
    esac
}

install_packages
success "System packages check complete."

# ------------------------------------------------------------------------------
# 2. Setup Font Directories
# ------------------------------------------------------------------------------
FONT_BASE_DIR="$HOME/.local/share/fonts"
NERD_DIR="$FONT_BASE_DIR/NerdFonts"
EMOJI_DIR="$FONT_BASE_DIR/Emoji"
TMP_DIR=$(mktemp -d -t fonts_setup_XXXXXX)

cleanup() {
    rm -rf "$TMP_DIR"
}
trap cleanup EXIT

mkdir -p "$NERD_DIR" "$EMOJI_DIR"

# ------------------------------------------------------------------------------
# 3. Download & Install FiraCode Nerd Font (Complete Suite)
# ------------------------------------------------------------------------------
info "Fetching official FiraCode Nerd Font release from GitHub..."
FIRA_URL="https://github.com/ryanoasis/nerd-fonts/releases/latest/download/FiraCode.tar.xz"

if curl -fsSL "$FIRA_URL" -o "$TMP_DIR/FiraCode.tar.xz"; then
    info "Extracting FiraCode Nerd Font (.ttf files)..."
    tar -xf "$TMP_DIR/FiraCode.tar.xz" -C "$NERD_DIR" --wildcards "*.ttf" 2>/dev/null || \
    tar -xf "$TMP_DIR/FiraCode.tar.xz" -C "$NERD_DIR" 2>/dev/null || true
    # Clean up non-font files if unpacked
    find "$NERD_DIR" -type f ! -name "*.ttf" ! -name "*.otf" -delete 2>/dev/null || true
    success "FiraCode Nerd Font installed to $NERD_DIR."
else
    warn "Failed to download FiraCode.tar.xz bundle; downloading standalone Regular TTF..."
    curl -fsSL -o "$NERD_DIR/FiraCodeNerdFont-Regular.ttf" \
        "https://raw.githubusercontent.com/ryanoasis/nerd-fonts/master/patched-fonts/FiraCode/Regular/FiraCodeNerdFont-Regular.ttf" 2>/dev/null || true
fi

# ------------------------------------------------------------------------------
# 4. Download & Install Symbols Nerd Font (All Glyphs & Icons)
# ------------------------------------------------------------------------------
info "Fetching Symbols Nerd Font (universal glyphs & icons)..."
SYMBOLS_URL="https://github.com/ryanoasis/nerd-fonts/releases/latest/download/NerdFontsSymbolsOnly.tar.xz"

if curl -fsSL "$SYMBOLS_URL" -o "$TMP_DIR/SymbolsOnly.tar.xz"; then
    tar -xf "$TMP_DIR/SymbolsOnly.tar.xz" -C "$NERD_DIR" --wildcards "*.ttf" 2>/dev/null || \
    tar -xf "$TMP_DIR/SymbolsOnly.tar.xz" -C "$NERD_DIR" 2>/dev/null || true
    find "$NERD_DIR" -type f ! -name "*.ttf" ! -name "*.otf" -delete 2>/dev/null || true
    success "Symbols Nerd Font (10,000+ icons & glyphs) installed."
else
    warn "Direct archive download failed; fetching standalone SymbolsNerdFontMono-Regular.ttf..."
    curl -fsSL -o "$NERD_DIR/SymbolsNerdFont-Regular.ttf" \
        "https://raw.githubusercontent.com/ryanoasis/nerd-fonts/master/patched-fonts/NerdFontsSymbolsOnly/SymbolsNerdFont-Regular.ttf" 2>/dev/null || true
fi

# ------------------------------------------------------------------------------
# 5. Download & Install Google Noto Color Emoji
# ------------------------------------------------------------------------------
info "Ensuring Google Noto Color Emoji is installed for vibrant terminal emojis..."
if [ ! -f "$EMOJI_DIR/NotoColorEmoji.ttf" ] && [ ! -f "/usr/share/fonts/truetype/noto/NotoColorEmoji.ttf" ]; then
    info "Downloading Noto Color Emoji font..."
    curl -fsSL -o "$EMOJI_DIR/NotoColorEmoji.ttf" \
        "https://raw.githubusercontent.com/google/fonts/main/ofl/notocoloremoji/NotoColorEmoji-Regular.ttf" 2>/dev/null || true
    success "Noto Color Emoji installed to $EMOJI_DIR."
else
    success "Noto Color Emoji is present on the system."
fi

# ------------------------------------------------------------------------------
# 6. Configure Fontconfig Fallbacks (~/.config/fontconfig/fonts.conf)
# ------------------------------------------------------------------------------
info "Configuring Fontconfig aliases & symbol/emoji fallback matrix..."
CONFIG_DIR="$HOME/.config/fontconfig"
mkdir -p "$CONFIG_DIR"

cat << 'EOF' > "$CONFIG_DIR/fonts.conf"
<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
<fontconfig>
    <!-- Preferred Monospace Font Stack with Nerd Fonts and Emoji Fallback -->
    <alias>
        <family>monospace</family>
        <prefer>
            <family>FiraCode Nerd Font</family>
            <family>Fira Code</family>
            <family>Symbols Nerd Font</family>
            <family>Symbols Nerd Font Mono</family>
            <family>Noto Color Emoji</family>
            <family>FontAwesome</family>
        </prefer>
    </alias>

    <!-- Preferred Sans-Serif Font Stack with Emoji Fallback -->
    <alias>
        <family>sans-serif</family>
        <prefer>
            <family>DejaVu Sans</family>
            <family>Noto Color Emoji</family>
            <family>Symbols Nerd Font</family>
        </prefer>
    </alias>

    <!-- Fix Color Emoji Rendering -->
    <match target="pattern">
        <test qual="any" name="family"><string>Noto Color Emoji</string></test>
        <edit name="scalable" mode="assign"><bool>true</bool></edit>
    </match>
</fontconfig>
EOF
success "Fontconfig fallback profile written to ~/.config/fontconfig/fonts.conf."

# ------------------------------------------------------------------------------
# 7. Refresh Font Cache
# ------------------------------------------------------------------------------
info "Refreshing system font cache with fc-cache..."
if command -v fc-cache >/dev/null 2>&1; then
    fc-cache -fv "$FONT_BASE_DIR" >/dev/null 2>&1 || true
    if [ "$IS_ROOT" = true ] || command -v sudo >/dev/null 2>&1; then
        sudo fc-cache -f >/dev/null 2>&1 || true
    fi
    success "Font cache refreshed."
else
    warn "fc-cache binary not found; please restart terminal to detect newly installed fonts."
fi

# ------------------------------------------------------------------------------
# 8. Visual Validation & Glyph Preview
# ------------------------------------------------------------------------------
echo ""
echo -e "${GREEN}${BOLD}============================================================${NC}"
echo -e "${GREEN}${BOLD}       Nerd Fonts, Symbols & Emojis Setup Complete!        ${NC}"
echo -e "${GREEN}${BOLD}============================================================${NC}"
echo ""
echo -e "${BOLD}1. Prompt Glyphs Check:${NC}"
echo -e "   Your Prompt Separator:  ${CYAN}user\033[0m\033[1;36m\033[0m\033[1;34mhost\033[0m"
echo -e "   Two-line Glyphs:        ${CYAN}┌──(userhost)-[~]\n   └─$ ${NC}"
echo ""
echo -e "${BOLD}2. Neowofetch Icon Bar Telemetry Check:${NC}"
echo -e "   Local IP:    \033[1;36mﭛ\033[0m 127.0.0.1"
echo -e "   Public IP:   \033[1;36m\033[0m 1.1.1.1"
echo -e "   Distro:      \033[1;36m\033[0m Linux"
echo -e "   Model:       \033[1;36m\033[0m Hardware"
echo -e "   CPU / Disk:  \033[1;36m\033[0m AMD/Intel   \033[1;36m\033[0m NVMe/SSD"
echo -e "   RAM / BT:    \033[1;36m\033[0m 16GB        \033[1;36m\033[0m Bluetooth"
echo -e "   Runtimes:    \033[1;36m\033[0m Python      \033[1;36m\033[0m Java        \033[1;36m\033[0m Node"
echo -e "   Shell / Up:  \033[1;36m\033[0m Zsh         \033[1;36m⏻\033[0m 42 days"
echo ""
echo -e "${BOLD}3. Emoji & Symbol Palette Check:${NC}"
echo -e "   Security & Recon:  💀 🔥 🚀 ⚡ 💻 🔍 🔒 🛡️ 🎯 📦 🌐 ⚙️"
echo -e "   Powerline Arrows:         "
echo ""
echo -e "${YELLOW}[Tip]${NC} If using an SSH client or GUI terminal (e.g. Windows Terminal, PuTTY, Alacritty, iTerm2):"
echo -e "      Set your terminal font to: ${CYAN}'FiraCode Nerd Font'${NC} or ${CYAN}'FiraCode NF'${NC}."
echo ""
