#!/bin/bash
set -e

# Deeplake FS Web Installer
# Downloads pre-compiled archives with bundled Node.js — no runtime dependencies needed!
# Users only need FUSE-T (macOS) or libfuse2 (Linux).
# Usage: curl -fsSL https://deeplake-fs.s3.amazonaws.com/install.sh | bash

APP_NAME="deeplake"
INSTALL_DIR="$HOME/.deeplake"

# Base URL for downloads
BASE_URL="https://deeplake-fs.s3.amazonaws.com"

# Colors (disable if not a terminal)
if [ -t 1 ]; then
    RED='\033[0;31m'
    GREEN='\033[0;32m'
    YELLOW='\033[0;33m'
    BLUE='\033[0;34m'
    NC='\033[0m'
else
    RED=''
    GREEN=''
    YELLOW=''
    BLUE=''
    NC=''
fi

# Detect platform
detect_platform() {
    local os arch

    os="$(uname -s)"
    arch="$(uname -m)"

    case "$os" in
        Darwin) os="darwin" ;;
        Linux)  os="linux" ;;
        MINGW*|MSYS*|CYGWIN*) os="windows" ;;
        *) echo -e "${RED}Error: Unsupported OS: $os${NC}" >&2; exit 1 ;;
    esac

    case "$arch" in
        x86_64|amd64) arch="x64" ;;
        aarch64|arm64) arch="arm64" ;;
        *) echo -e "${RED}Error: Unsupported architecture: $arch${NC}" >&2; exit 1 ;;
    esac

    echo "${os}-${arch}"
}

# Print banner
print_banner() {
echo ""
echo "╔═════════════════════════════════════════════════════════════════════╗"
echo "║                                                                     ║"
echo "║   ██████╗ ███████╗███████╗██████╗ ██╗      █████╗ ██╗  ██╗███████╗  ║"
echo "║   ██╔══██╗██╔════╝██╔════╝██╔══██╗██║     ██╔══██╗██║ ██╔╝██╔════╝  ║"
echo "║   ██║  ██║█████╗  █████╗  ██████╔╝██║     ███████║█████╔╝ █████╗    ║"
echo "║   ██║  ██║██╔══╝  ██╔══╝  ██╔═══╝ ██║     ██╔══██║██╔═██╗ ██╔══╝    ║"
echo "║   ██████╔╝███████╗███████╗██║     ███████╗██║  ██║██║  ██╗███████╗  ║"
echo "║   ╚═════╝ ╚══════╝╚══════╝╚═╝     ╚══════╝╚═╝  ╚═╝╚═╝  ╚═╝╚══════╝  ║"
echo "║                                                                     ║"
echo "║                                                                     ║"
echo "║            The filesystem that gives AI agents memory.              ║"
echo "║                                                                     ║"
echo "╚═════════════════════════════════════════════════════════════════════╝"
}

# Check for required tools
check_command() {
    command -v "$1" >/dev/null 2>&1
}

# Ask user for confirmation (defaults to Yes)
confirm_install() {
    local pkg_name="$1"
    echo ""
    echo -e "${BLUE}Deeplake FS requires $pkg_name to work.${NC}"
    echo -e "Would you like to install it now? [Y/n] \c"

    # When piped (curl | bash), stdin is the script itself — reopen from terminal
    if [ -t 0 ]; then
        read -r answer
    elif [ -e /dev/tty ]; then
        read -r answer < /dev/tty
    else
        answer="y"  # Non-interactive: auto-accept
    fi

    case "$answer" in
        [nN]|[nN][oO]) return 1 ;;
        *) return 0 ;;  # Default is Yes
    esac
}

# Check if user can run sudo
can_sudo() {
    if [ "$EUID" -eq 0 ]; then
        return 0  # Already root
    fi
    if check_command sudo && sudo -n true 2>/dev/null; then
        return 0  # Can sudo without password
    fi
    if check_command sudo && sudo -v 2>/dev/null; then
        return 0  # Can sudo with password (already authenticated)
    fi
    return 1
}

# Install libfuse on Linux
install_libfuse_linux() {
    echo -e "${YELLOW}libfuse is required but not installed.${NC}"
    echo ""

    # Check if we can install packages
    if ! can_sudo; then
        echo -e "${YELLOW}sudo is required to install libfuse.${NC}"
        echo ""
        echo "Please install it first, then re-run this installer:"
        echo ""
        if check_command apt-get; then
            echo "  sudo apt install -y libfuse2 fuse"
        elif check_command dnf; then
            echo "  sudo dnf install -y fuse fuse-libs"
        elif check_command yum; then
            echo "  sudo yum install -y fuse fuse-libs"
        elif check_command pacman; then
            echo "  sudo pacman -S fuse2"
        elif check_command apk; then
            echo "  sudo apk add fuse"
        else
            echo "  Ubuntu/Debian: sudo apt install libfuse2 fuse"
            echo "  Fedora/RHEL:   sudo dnf install fuse fuse-libs"
            echo "  Arch:          sudo pacman -S fuse2"
            echo "  Alpine:        sudo apk add fuse"
        fi
        echo ""
        echo "Then re-run:"
        echo "  curl -fsSL https://deeplake.ai/install | bash"
        echo ""
        exit 1
    fi

    # Detect package manager and install
    if check_command apt-get; then
        echo "Installing libfuse via apt..."
        sudo apt-get update -qq
        sudo apt-get install -y libfuse2 fuse || sudo apt-get install -y libfuse-dev fuse
    elif check_command dnf; then
        echo "Installing libfuse via dnf..."
        sudo dnf install -y fuse fuse-libs
    elif check_command yum; then
        echo "Installing libfuse via yum..."
        sudo yum install -y fuse fuse-libs
    elif check_command pacman; then
        echo "Installing libfuse via pacman..."
        sudo pacman -S --noconfirm fuse2
    elif check_command apk; then
        echo "Installing libfuse via apk..."
        sudo apk add fuse
    else
        echo -e "${RED}Error: Could not detect package manager.${NC}"
        echo ""
        echo "Please install libfuse manually, then re-run this installer:"
        echo ""
        echo "  Ubuntu/Debian: sudo apt install libfuse2 fuse"
        echo "  Fedora/RHEL:   sudo dnf install fuse fuse-libs"
        echo "  Arch:          sudo pacman -S fuse2"
        echo "  Alpine:        sudo apk add fuse"
        echo ""
        echo "Then re-run:"
        echo "  curl -fsSL https://deeplake.ai/install | bash"
        echo ""
        exit 1
    fi
}

# Check and install FUSE
check_and_install_fuse() {
    if [ "$(uname -s)" = "Linux" ]; then
        # Both libfuse AND fusermount binary are required.
        # fuse-libs alone (libfuse.so) is not enough; the fuse package provides fusermount.
        if ! check_command fusermount && ! check_command fusermount3; then
            echo ""
            if ! can_sudo; then
                # No sudo — tell the user exactly what to run, then re-run
                install_libfuse_linux
            elif confirm_install "libfuse (FUSE for Linux)"; then
                install_libfuse_linux
            else
                echo ""
                echo "Installation cancelled. FUSE is required for Deeplake FS."
                echo "Install it manually and re-run this installer:"
                echo "  curl -fsSL https://deeplake.ai/install | bash"
                exit 1
            fi
            echo ""
        fi

        # Verify installation — fusermount binary must exist
        if check_command fusermount || check_command fusermount3; then
            echo -e "  ${GREEN}Found FUSE: OK${NC}"
        else
            echo -e "${RED}Error: FUSE installation failed. fusermount binary not found.${NC}"
            exit 1
        fi

    elif [ "$(uname -s)" = "Darwin" ]; then
        # macOS — check for FUSE-T first (preferred), then macFUSE as fallback
        if [ -f "/usr/local/lib/libfuse-t.dylib" ]; then
            echo -e "  ${GREEN}Found FUSE-T: OK${NC}"
        elif [ -f "/usr/local/lib/libfuse.2.dylib" ] || [ -f "/opt/homebrew/lib/libfuse.2.dylib" ]; then
            echo -e "  ${GREEN}Found macFUSE: OK${NC}"
            echo -e "  ${YELLOW}Tip: Consider switching to FUSE-T (no kernel extension required):${NC}"
            echo -e "       brew install --cask fuse-t"
        else
            echo ""
            echo -e "${YELLOW}No FUSE implementation found. FUSE is required for Deeplake FS.${NC}"
            echo ""

            # Try to install FUSE-T via Homebrew
            if check_command brew; then
                if confirm_install "FUSE-T (macOS FUSE, no kernel extension required)"; then
                    echo "Installing FUSE-T via Homebrew..."
                    echo ""
                    if brew install --cask fuse-t; then
                        echo ""
                        # Verify installation
                        if [ -f "/usr/local/lib/libfuse-t.dylib" ]; then
                            echo -e "  ${GREEN}FUSE-T installed and verified!${NC}"
                        else
                            echo -e "  ${GREEN}FUSE-T installed successfully!${NC}"
                        fi
                    else
                        echo ""
                        echo -e "${RED}Error: Failed to install FUSE-T via Homebrew.${NC}"
                        echo ""
                        echo "Please install manually:"
                        echo "  brew install --cask fuse-t"
                        echo ""
                        exit 1
                    fi
                else
                    echo ""
                    echo "Installation cancelled. FUSE is required for Deeplake FS."
                    echo "Install it manually and re-run this installer:"
                    echo "  brew install --cask fuse-t"
                    exit 1
                fi
            else
                echo -e "${RED}Error: Homebrew not found. Cannot auto-install FUSE-T.${NC}"
                echo ""
                echo "Option 1: Install Homebrew first, then re-run this installer:"
                echo "  /bin/bash -c \"\$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\""
                echo ""
                echo "Option 2: Install FUSE-T manually from:"
                echo "  https://www.fuse-t.org/"
                echo ""
                exit 1
            fi
        fi
    fi
}

# Main installation
main() {
    print_banner

    PLATFORM=$(detect_platform)
    echo "Installing Deeplake FS for $PLATFORM..."
    echo ""

    # Check prerequisites (Node.js is bundled — only FUSE needed)
    echo "Checking prerequisites..."
    check_and_install_fuse

    # Create install directory
    echo ""
    echo "Creating install directory..."
    mkdir -p "$INSTALL_DIR"
    cd "$INSTALL_DIR"

    # Download the platform-specific archive
    ARCHIVE_NAME="deeplake-${PLATFORM}.tar.gz"
    DOWNLOAD_URL="${BASE_URL}/${ARCHIVE_NAME}"

    echo "Downloading Deeplake FS..."
    echo "  URL: $DOWNLOAD_URL"

    if ! curl -fsSL -o "$ARCHIVE_NAME" "$DOWNLOAD_URL"; then
        echo ""
        echo -e "${RED}Error: Failed to download from $DOWNLOAD_URL${NC}"
        echo ""
        echo "Please check:"
        echo "  1. Your internet connection"
        echo "  2. The download URL is correct"
        echo "  3. Your platform ($PLATFORM) is supported"
        echo ""
        exit 1
    fi

    # Verify the archive is valid
    if check_command file; then
        if ! file "$ARCHIVE_NAME" | grep -q "gzip compressed data"; then
            echo ""
            echo -e "${RED}Error: Downloaded file is not a valid archive.${NC}"
            echo "The server may be returning an error page."
            rm -f "$ARCHIVE_NAME"
            exit 1
        fi
    else
        # Fallback: try to list archive contents
        if ! tar -tzf "$ARCHIVE_NAME" >/dev/null 2>&1; then
            echo ""
            echo -e "${RED}Error: Downloaded file is not a valid archive.${NC}"
            rm -f "$ARCHIVE_NAME"
            exit 1
        fi
    fi

    # Verify checksum if sha256sum is available
    if check_command sha256sum || check_command shasum; then
        echo "Verifying checksum..."
        CHECKSUM_URL="${BASE_URL}/SHA256SUMS.txt"
        if curl -fsSL -o SHA256SUMS.txt "$CHECKSUM_URL" 2>/dev/null; then
            EXPECTED_SUM=$(grep "$ARCHIVE_NAME" SHA256SUMS.txt | awk '{print $1}')
            if [ -n "$EXPECTED_SUM" ]; then
                if check_command sha256sum; then
                    ACTUAL_SUM=$(sha256sum "$ARCHIVE_NAME" | awk '{print $1}')
                else
                    ACTUAL_SUM=$(shasum -a 256 "$ARCHIVE_NAME" | awk '{print $1}')
                fi
                if [ "$EXPECTED_SUM" = "$ACTUAL_SUM" ]; then
                    echo -e "  ${GREEN}Checksum verified${NC}"
                else
                    echo -e "${RED}Error: Checksum mismatch!${NC}"
                    echo "  Expected: $EXPECTED_SUM"
                    echo "  Got:      $ACTUAL_SUM"
                    rm -f "$ARCHIVE_NAME" SHA256SUMS.txt
                    exit 1
                fi
            fi
            rm -f SHA256SUMS.txt
        fi
    fi

    # Extract (BSD tar on macOS doesn't support --warning flag)
    echo "Extracting..."
    tar -xzf "$ARCHIVE_NAME" 2>/dev/null
    rm "$ARCHIVE_NAME"

    # Make binaries executable
    chmod +x "$INSTALL_DIR/deeplake"
    chmod +x "$INSTALL_DIR/node"

    # Create global command symlink
    echo "Creating 'deeplake' command..."

    # Try /usr/local/bin first, fall back to ~/.local/bin
    if [ -w /usr/local/bin ] || [ "$EUID" -eq 0 ]; then
        BIN_PATH="/usr/local/bin/deeplake"
        ln -sf "$INSTALL_DIR/deeplake" "$BIN_PATH"
        echo -e "  ${GREEN}Installed to: $BIN_PATH${NC}"
    else
        # Create user-local bin directory
        mkdir -p "$HOME/.local/bin"
        BIN_PATH="$HOME/.local/bin/deeplake"
        ln -sf "$INSTALL_DIR/deeplake" "$BIN_PATH"
        echo -e "  ${GREEN}Installed to: $BIN_PATH${NC}"

        # Check if ~/.local/bin is in PATH
        if [[ ":$PATH:" != *":$HOME/.local/bin:"* ]]; then
            echo ""
            echo -e "  ${YELLOW}Note: Add ~/.local/bin to your PATH:${NC}"
            echo "    echo 'export PATH=\"\$HOME/.local/bin:\$PATH\"' >> ~/.bashrc"
            echo "    source ~/.bashrc"
        fi
    fi

    # Success message
    echo ""
    echo "======================================================================="
    echo ""
    echo -e "  ${GREEN}Deeplake FS installed successfully!${NC}"
    echo ""
    echo "  Installation: $INSTALL_DIR"
    echo "  Command:      deeplake"
    echo ""
    echo "======================================================================="
    echo ""
    echo "  Quick Start:"
    echo ""
    echo "    1. Initialize (interactive setup):"
    echo -e "       ${BLUE}deeplake init${NC}"
    echo ""
    echo "    2. Start the filesystem:"
    echo -e "       ${BLUE}deeplake mount --all${NC}"
    echo ""
    echo "    3. Check status:"
    echo -e "       ${BLUE}deeplake list${NC}"
    echo ""
    echo "  After mounting, use the folder with any AI assistant."
    echo "  Files persist in Deeplake Cloud and sync across all clients."
    echo ""
    echo "======================================================================="
    echo ""
}

main "$@"
