#!/bin/bash

# Path: scripts/base.sh

set -e

BLUE='\033[1;34m'
YELLOW='\033[1;33m'
GREEN='\033[1;32m'
RED='\033[1;31m'
NC='\033[0m'

DOTFILES_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
REPO_ROOT="$(dirname "$DOTFILES_DIR")"
source "$DOTFILES_DIR/lib/distro.sh"

echo -e "${BLUE}    LOG:${YELLOW} Initializing Base System Layer...${NC}"

# Confirm Architecture
ARCH=$(uname -m)
if [ "$ARCH" != "x86_64" ] && [ "$ARCH" != "aarch64" ]; then
    echo -e "${RED}    ERROR: Unsupported architecture: $ARCH${NC}"
    exit 1
fi

# Package Installation
PACKAGES=(
    curl wget git sudo
    zsh tmux
    unzip tar gzip
    build-essential
    openssl
    python bison mercurial
    ripgrep fd bat fzf jq
    btop httpie gnupg
    zoxide stow
    bind nmap socat tcpdump net-tools
    strace gdb hexyl
    ninja-build libcurl4-openssl-dev
    just
)

FINAL_PACKAGES=()

for pkg in "${PACKAGES[@]}"; do
    case "$pkg" in
        "build-essential")
            if is_arch_family; then
                FINAL_PACKAGES+=(base-devel)
            elif is_debian_family; then
                FINAL_PACKAGES+=(build-essential)
            elif is_fedora_family; then
                FINAL_PACKAGES+=(gcc gcc-c++ make patch)
            fi
            continue
            ;;
        "python")
            if is_arch_family; then
                FINAL_PACKAGES+=(python)
            elif is_debian_family; then
                FINAL_PACKAGES+=(python3 python3-pip python3-venv)
            elif is_fedora_family; then
                FINAL_PACKAGES+=(python3 python3-pip)
            fi
            continue
            ;;
        "fd")
            if is_arch_family; then
                FINAL_PACKAGES+=(fd)
            elif is_debian_family || is_fedora_family; then
                FINAL_PACKAGES+=(fd-find)
            fi
            continue
            ;;
        "bat")
            FINAL_PACKAGES+=(bat)
            continue
            ;;
        "openssl")
            if is_arch_family; then
                FINAL_PACKAGES+=(openssl)
            elif is_debian_family; then
                FINAL_PACKAGES+=(libssl-dev)
            elif is_fedora_family; then
                FINAL_PACKAGES+=(openssl openssl-devel)
            fi
            continue
            ;;
        "bind")
            if is_arch_family; then
                FINAL_PACKAGES+=(bind)
            elif is_debian_family; then
                FINAL_PACKAGES+=(dnsutils)
            elif is_fedora_family; then
                FINAL_PACKAGES+=(bind-utils)
            fi
            continue
            ;;
        "ninja-build")
            if is_arch_family; then
                FINAL_PACKAGES+=(ninja)
            elif is_debian_family || is_fedora_family; then
                FINAL_PACKAGES+=(ninja-build)
            fi
            continue
            ;;
        "libcurl4-openssl-dev")
            if is_arch_family; then
                FINAL_PACKAGES+=(curl)
            elif is_debian_family; then
                FINAL_PACKAGES+=(libcurl4-openssl-dev)
            elif is_fedora_family; then
                FINAL_PACKAGES+=(libcurl-devel)
            fi
            continue
            ;;
        "gnupg")
            if is_fedora_family; then
                FINAL_PACKAGES+=(gnupg2)
            else
                FINAL_PACKAGES+=(gnupg)
            fi
            continue
            ;;
        *)
    esac

    FINAL_PACKAGES+=("$pkg")
done

if is_debian_family; then
    FINAL_PACKAGES+=(ca-certificates bsdmainutils pkg-config cmake)
fi

if is_fedora_family; then
    FINAL_PACKAGES+=(ca-certificates pkgconf-pkg-config cmake)
fi

echo -e "${BLUE}    LOG:${YELLOW} Installing: ${NC}${FINAL_PACKAGES[*]}"

install_status=0
install_packages "${FINAL_PACKAGES[@]}" || install_status=$?

if [ "$install_status" -eq 42 ]; then
    exit 0
elif [ "$install_status" -ne 0 ]; then
    exit "$install_status"
fi

if is_debian_family || is_fedora_family; then
    echo -e "${BLUE}    LOG:${YELLOW} Fixing fd/bat binary names when needed...${NC}"
    [ -f /usr/bin/fdfind ] && sudo ln -sf /usr/bin/fdfind /usr/local/bin/fd
    [ -f /usr/bin/batcat ] && sudo ln -sf /usr/bin/batcat /usr/local/bin/bat
fi

# Moving Pre-Built bin to .local/bin
mkdir -p "$HOME/.local/bin"
cp -f "$REPO_ROOT/bin/"* "$HOME/.local/bin/"
chmod +x "$HOME/.local/bin/"*

if ! command -v rclone &> /dev/null; then
    echo -e "${BLUE}    LOG:${YELLOW} Installing Rclone (Latest)...${NC}"
    curl https://rclone.org/install.sh | sudo bash
fi

if ! command -v earthly &> /dev/null; then
    echo -e "${BLUE}    LOG:${YELLOW} Installing Earthly CLI...${NC}"

    case "$ARCH" in
        x86_64)
            EARTHLY_ARCH="amd64"
            ;;
        aarch64)
            EARTHLY_ARCH="arm64"
            ;;
    esac

    curl -fLsS "https://github.com/earthly/earthly/releases/latest/download/earthly-linux-${EARTHLY_ARCH}" \
        -o "$HOME/.local/bin/earthly"
    chmod +x "$HOME/.local/bin/earthly"
fi

# Docker Installation
if command -v docker &> /dev/null; then
    echo -e "${GREEN}    LOG: Docker is already installed.${NC}"
else
    if grep -qEi "(Microsoft|WSL)" /proc/version &> /dev/null; then
        echo -e "${RED}    LOG: WSL Detected! Skipping Native Docker.${NC}"
        echo -e "${RED}    >>> Please install Docker Desktop on Windows.${NC}"
    else
        echo -e "${BLUE}    LOG:${YELLOW} Installing Native Docker...${NC}"
        if is_arch_family; then
            sudo pacman -S --noconfirm --needed docker docker-compose
            sudo systemctl enable --now docker
        elif is_debian_family; then
            curl -fsSL https://get.docker.com | sh
        elif is_fedora_family; then
            if is_atomic_fedora; then
                echo -e "${YELLOW}    NOTE:${NC} Skipping native Docker auto-install on rpm-ostree systems."
                echo -e "${YELLOW}    NOTE:${NC} After reboot, install your preferred container runtime separately if needed."
            else
                sudo dnf install -y moby-engine docker-compose
                sudo systemctl enable --now docker
            fi
        fi

        # Add user to group
        if getent group docker >/dev/null 2>&1; then
            sudo usermod -aG docker $(whoami)
        fi
    fi
fi

# 4. Zsh & Configuration
if [ ! -d "$HOME/.oh-my-zsh" ]; then
    echo -e "${BLUE}    LOG:${YELLOW} Installing Oh My Zsh...${NC}"
    sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" "" --unattended
fi

# Plugins
ZSH_CUSTOM="${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}"
mkdir -p "$ZSH_CUSTOM/plugins"
[ ! -d "$ZSH_CUSTOM/plugins/zsh-syntax-highlighting" ] && git clone https://github.com/zsh-users/zsh-syntax-highlighting.git "$ZSH_CUSTOM/plugins/zsh-syntax-highlighting"
[ ! -d "$ZSH_CUSTOM/plugins/zsh-autosuggestions" ] && git clone https://github.com/zsh-users/zsh-autosuggestions "$ZSH_CUSTOM/plugins/zsh-autosuggestions"

# 5. Git Credentials (WSL Bridge)
if grep -qEi "(Microsoft|WSL)" /proc/version &> /dev/null; then
    GCM_WIN="/mnt/c/Program Files/Git/mingw64/bin/git-credential-manager.exe"
    [ -f "$GCM_WIN" ] && git config --global credential.helper "! \"$GCM_WIN\""
else
    git config --global credential.helper 'cache --timeout=43200'
fi

# 6. Cleanup & Secrets
rm -f "$HOME/.zshrc" "$HOME/.zsh_aliases"
touch "$HOME/.zsh_secrets"

# 7. Set Shell
if [ "$SHELL" != "$(which zsh)" ]; then
    sudo chsh -s "$(which zsh)" $(whoami)
fi

echo -e "${GREEN}    LOG: Base System Setup Complete.${NC}"
