#!/usr/bin/env bash
set -euo pipefail

# OrionChain Installer
# https://orionchain.clickswave.org
# © Clickswave. All rights reserved.

ORION_VERSION="${ORION_VERSION:-0.0.1}"
BINARY_CHANNEL="${BINARY_CHANNEL:-release}"
INSTALL_DIR="/opt/orionchain/bin"
PACKAGES_URL="https://bins.crossfyre.io"
AGREE_TO_TERMS=false

# Parse flags
for arg in "$@"; do
    case "$arg" in
        --agree-to-terms) AGREE_TO_TERMS=true ;;
    esac
done

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
BOLD='\033[1m'
RESET='\033[0m'

print_banner() {
    echo -e "${CYAN}"
    echo "  ___       _              ____ _           _       "
    echo " / _ \ _ __(_) ___  _ __  / ___| |__   __ _(_)_ __  "
    echo "| | | | '__| |/ _ \| '_ \| |   | '_ \ / _\` | | '_ \ "
    echo "| |_| | |  | | (_) | | | | |___| | | | (_| | | | | |"
    echo " \___/|_|  |_|\___/|_| |_|\____|_| |_|\__,_|_|_| |_|"
    echo -e "${RESET}"
    echo -e "${BOLD}  OrionChain - Offensive Security Toolkit${RESET}"
    echo -e "  by Clickswave  •  https://orionchain.clickswave.org"
    echo ""
}

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

print_disclaimer() {
    echo -e "${YELLOW}  ┌─────────────────────────────────────────────────────────┐${RESET}"
    echo -e "${YELLOW}  │                      DISCLAIMER                         │${RESET}"
    echo -e "${YELLOW}  └─────────────────────────────────────────────────────────┘${RESET}"
    echo ""
    echo -e "  OrionChain is an ${BOLD}offensive security toolkit${RESET} intended for"
    echo -e "  authorized penetration testing and security research only."
    echo -e "  Unauthorized use against systems you do not own or have"
    echo -e "  explicit permission to test is ${RED}illegal and strictly prohibited${RESET}."
    echo ""
    echo -e "  ${BOLD}This installer will:${RESET}"
    echo -e "    • Install the ${CYAN}orion${RESET} binary to ${BOLD}/opt/orionchain/bin/${RESET}"
    echo -e "    • Add ${BOLD}/opt/orionchain/bin${RESET} to your PATH"
    echo -e "    • Require ${BOLD}sudo${RESET} to write to /opt"
    echo ""
    echo -e "  ${BOLD}Review the installer before running:${RESET}"
    echo -e "    ${CYAN}https://orionchain.clickswave.org/install.sh${RESET}"
    echo ""
    echo -e "${YELLOW}  By proceeding, you confirm that you are a security professional${RESET}"
    echo -e "${YELLOW}  and will use these tools only on authorized systems.${RESET}"
    echo ""

    if [ "$AGREE_TO_TERMS" = true ]; then
        success "Terms accepted via --agree-to-terms flag."
        echo ""
        return
    fi

    echo -ne "  Proceed with installation? [y/N] "
    read -r REPLY </dev/tty
    echo ""
    case "$REPLY" in
        y|Y|yes|YES)
            success "Proceeding with installation..."
            echo ""
            ;;
        *)
            echo -e "  Installation cancelled."
            echo ""
            exit 0
            ;;
    esac
}

detect_platform() {
    OS="$(uname -s)"
    ARCH="$(uname -m)"

    case "$OS" in
        Linux)  PLATFORM="linux" ;;
        Darwin) PLATFORM="darwin" ;;
        *) error "Unsupported OS: $OS" ;;
    esac

    case "$ARCH" in
        x86_64)  ARCH_TAG="x86_64" ;;
        aarch64|arm64) ARCH_TAG="aarch64" ;;
        *) error "Unsupported architecture: $ARCH" ;;
    esac

    info "Detected platform: ${PLATFORM}/${ARCH_TAG}"
}

check_dependencies() {
    for cmd in curl unzip docker; do
        if ! command -v "$cmd" &>/dev/null; then
            if [ "$cmd" = "docker" ]; then
                warn "Docker not found - required for 'orion db' commands."
            else
                error "'$cmd' is required but not installed."
            fi
        fi
    done
}

resolve_version() {
    info "Using version: ${ORION_VERSION} (${BINARY_CHANNEL})"
}

download_tool() {
    local TOOL="$1"
    local ZIP="${TOOL}-${BINARY_CHANNEL}-${ORION_VERSION}.zip"
    local DOWNLOAD_URL="${PACKAGES_URL}/${ZIP}"
    local TMP_DIR
    TMP_DIR="$(mktemp -d)"

    info "Downloading ${TOOL} from: ${DOWNLOAD_URL}"
    HTTP_CODE="$(curl -L -o "${TMP_DIR}/${ZIP}" -w "%{http_code}" -# "$DOWNLOAD_URL" 2>&1 || true)"
    # strip progress bar noise, keep last 3 chars (the HTTP code)
    HTTP_CODE="${HTTP_CODE: -3}"
    echo ""
    info "HTTP status: ${HTTP_CODE}"
    if [ "$HTTP_CODE" != "200" ]; then
        warn "Skipping ${TOOL} - download failed (HTTP ${HTTP_CODE})"
        rm -rf "$TMP_DIR"
        return 0
    fi
    success "Downloaded ${ZIP}"

    info "Extracting ${TOOL}..."
    unzip "${TMP_DIR}/${ZIP}" -d "$TMP_DIR"

    sudo mv "${TMP_DIR}/${TOOL}" "${INSTALL_DIR}/${TOOL}"
    sudo chmod 755 "${INSTALL_DIR}/${TOOL}"

    rm -rf "$TMP_DIR"
    success "${TOOL} → ${INSTALL_DIR}/${TOOL}"
}

download_all() {
    download_tool "orion"
}

configure_path() {
    local PATH_EXPORT="export PATH=\"\$PATH:${INSTALL_DIR}\""

    declare -A SHELLS
    SHELLS[bash]="${HOME}/.bashrc"
    SHELLS[zsh]="${HOME}/.zshrc"

    for SH in "${!SHELLS[@]}"; do
        RC="${SHELLS[$SH]}"
        if ! grep -q "${INSTALL_DIR}" "$RC" 2>/dev/null; then
            echo "" >> "$RC"
            echo "# OrionChain" >> "$RC"
            echo "$PATH_EXPORT" >> "$RC"
            success "Added ${INSTALL_DIR} to PATH in ${RC}"
        else
            info "PATH already configured in ${RC}"
        fi
    done

    # fish
    FISH_RC="${HOME}/.config/fish/config.fish"
    if command -v fish &>/dev/null; then
        if ! grep -q "${INSTALL_DIR}" "$FISH_RC" 2>/dev/null; then
            mkdir -p "$(dirname "$FISH_RC")"
            echo "" >> "$FISH_RC"
            echo "# OrionChain" >> "$FISH_RC"
            echo "fish_add_path ${INSTALL_DIR}" >> "$FISH_RC"
            success "Added ${INSTALL_DIR} to PATH in ${FISH_RC}"
        else
            info "PATH already configured in ${FISH_RC}"
        fi
    fi

    RC_FILE="${HOME}/.bashrc"
}

print_done() {
    echo ""
    success "OrionChain installed successfully!"
    echo ""
    echo -e "  ${BOLD}Installed binaries:${RESET}"
    if [ -f "${INSTALL_DIR}/orion" ]; then
        echo -e "    ${GREEN}✓${RESET} ${INSTALL_DIR}/orion"
    else
        echo -e "    ${RED}✗${RESET} ${INSTALL_DIR}/orion (missing)"
    fi
    echo ""
    echo -e "  ${BOLD}Next steps:${RESET}"
    echo "    1. Restart your terminal or run: source ${RC_FILE}"
    echo "    2. Run: orion init"
    echo "    3. Run: orion install all"
    echo ""
    echo -e "  ${CYAN}Docs:${RESET} https://orionchain.clickswave.org/docs"
    echo -e "  ${CYAN}Support:${RESET} support@clickswave.org"
    echo ""
}

main() {
    print_banner
    print_disclaimer
    if [ "$EUID" -ne 0 ]; then
        info "Requesting sudo for /opt/orionchain..."
        sudo -v || error "sudo access required to install to /opt/orionchain"
    fi
    detect_platform
    check_dependencies
    info "Creating install directory: ${INSTALL_DIR}"
    sudo mkdir -p "$INSTALL_DIR"
    sudo chown "$(id -u):$(id -g)" "$INSTALL_DIR"
    resolve_version
    download_all
    configure_path
    print_done
}

main "$@"
