#!/bin/sh
# ==============================================================================
# eprobe: Tactical Ephemeral eBPF Incident Response Toolkit Installer
# Usage:
#   curl -sSL https://get.eprobe.io | sh
#   curl -sSL https://eprobe.io/install.sh | sh
# ==============================================================================
set -e

# Terminal formatting
if [ -t 1 ] && [ -z "${NO_COLOR}" ]; then
  BOLD="\033[1m"
  GREEN="\033[32m"
  CYAN="\033[36m"
  YELLOW="\033[33m"
  RED="\033[31m"
  RESET="\033[0m"
else
  BOLD=""
  GREEN=""
  CYAN=""
  YELLOW=""
  RED=""
  RESET=""
fi

log_info() {
  printf "${CYAN}ℹ %s${RESET}\n" "$1"
}

log_success() {
  printf "${GREEN}✔ %s${RESET}\n" "$1"
}

log_warn() {
  printf "${YELLOW}⚠ %s${RESET}\n" "$1"
}

log_error() {
  printf "${RED}✖ %s${RESET}\n" "$1" >&2
}

printf "${BOLD}======================================================${RESET}\n"
printf "${BOLD} eprobe: Ephemeral eBPF Incident Response Toolkit   ${RESET}\n"
printf "${BOLD} Official Project & Portal: https://eprobe.io/       ${RESET}\n"
printf "${BOLD}======================================================${RESET}\n\n"

# 1. OS Verification (Linux only)
OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
if [ "$OS" != "linux" ]; then
  log_error "eprobe requires Linux kernel with eBPF CO-RE support (Kernel 5.8+)."
  log_error "Detected operating system: ${OS} (unsupported)."
  exit 1
fi

# 2. Architecture Verification (x86_64 / amd64)
ARCH="$(uname -m)"
case "$ARCH" in
  x86_64|amd64)
    BINARY_ARCH="amd64"
    ;;
  *)
    log_error "eprobe currently distributes static binaries for Linux amd64 (x86_64)."
    log_error "Detected architecture: ${ARCH} (unsupported)."
    exit 1
    ;;
esac

# 3. Kernel BTF Check
if [ ! -f /sys/kernel/btf/vmlinux ]; then
  log_warn "/sys/kernel/btf/vmlinux not found on this host."
  log_warn "eprobe utilizes CO-RE (Compile Once - Run Everywhere) and requires Kernel 5.8+ with BTF enabled."
fi

# 4. Target Directory Resolution
if [ -n "${EPROBE_INSTALL_DIR}" ]; then
  INSTALL_DIR="${EPROBE_INSTALL_DIR}"
elif [ -w "/usr/local/bin" ]; then
  INSTALL_DIR="/usr/local/bin"
elif [ "$(id -u)" -eq 0 ]; then
  INSTALL_DIR="/usr/local/bin"
elif [ -d "${HOME}/.local/bin" ] && [ -w "${HOME}/.local/bin" ]; then
  INSTALL_DIR="${HOME}/.local/bin"
else
  INSTALL_DIR="."
fi

TARGET_BIN="${INSTALL_DIR}/eprobe"
TMP_BIN="/tmp/eprobe.$$.tmp"

PRIMARY_URL="https://github.com/dimitribellini/eprobe-cli/releases/latest/download/eprobe-linux-${BINARY_ARCH}"
FALLBACK_URL="https://github.com/dimitribellini/eprobe-cli/releases/download/v0.0.83/eprobe-v0.0.83-linux-${BINARY_ARCH}"

log_info "Downloading latest eprobe static binary (Linux ${BINARY_ARCH})..."

DOWNLOADED=0
if command -v curl >/dev/null 2>&1; then
  if curl -sSL --fail "${PRIMARY_URL}" -o "${TMP_BIN}" 2>/dev/null; then
    DOWNLOADED=1
  elif curl -sSL --fail "${FALLBACK_URL}" -o "${TMP_BIN}" 2>/dev/null; then
    DOWNLOADED=1
  fi
elif command -v wget >/dev/null 2>&1; then
  if wget -q -O "${TMP_BIN}" "${PRIMARY_URL}" 2>/dev/null; then
    DOWNLOADED=1
  elif wget -q -O "${TMP_BIN}" "${FALLBACK_URL}" 2>/dev/null; then
    DOWNLOADED=1
  fi
else
  log_error "Neither 'curl' nor 'wget' was found on this system. Please install curl or wget."
  exit 1
fi

if [ "$DOWNLOADED" -ne 1 ] || [ ! -s "${TMP_BIN}" ]; then
  rm -f "${TMP_BIN}"
  log_error "Failed to download eprobe binary from GitHub Releases."
  log_error "Please check network connectivity or visit: https://github.com/dimitribellini/eprobe-cli/releases"
  exit 1
fi

chmod +x "${TMP_BIN}"

# 5. Installation
mkdir -p "${INSTALL_DIR}" 2>/dev/null || true

if [ -w "${INSTALL_DIR}" ] || [ "$(id -u)" -eq 0 ]; then
  mv -f "${TMP_BIN}" "${TARGET_BIN}"
else
  if command -v sudo >/dev/null 2>&1; then
    log_info "Elevating permissions to install to ${INSTALL_DIR}..."
    sudo mv -f "${TMP_BIN}" "${TARGET_BIN}"
    sudo chmod +x "${TARGET_BIN}"
  else
    TARGET_BIN="./eprobe"
    mv -f "${TMP_BIN}" "${TARGET_BIN}"
    log_warn "Could not write to ${INSTALL_DIR} and sudo is unavailable."
    log_info "Installed locally to ${TARGET_BIN}"
  fi
fi

# 6. Verify and Print Next Steps
VERSION_INFO="$("${TARGET_BIN}" version 2>/dev/null || echo "installed")"
log_success "eprobe installed successfully to ${TARGET_BIN} (${VERSION_INFO})!"

printf "\n${BOLD}Quick Start Incident Triage Recipes:${RESET}\n"
if [ "${INSTALL_DIR}" = "/usr/local/bin" ] || [ "${INSTALL_DIR}" = "${HOME}/.local/bin" ]; then
  printf "  ${CYAN}sudo eprobe run app/docker-monitor${RESET}      # Triage container CPU/memory & block I/O\n"
  printf "  ${CYAN}sudo eprobe run perf/stall-tracer${RESET}       # Triage off-CPU stalls & storage freezes\n"
  printf "  ${CYAN}sudo eprobe run app/universal-tls-sniffer${RESET} # Plaintext HTTPS/HTTP2 inspection\n"
else
  printf "  ${CYAN}sudo ${TARGET_BIN} run app/docker-monitor${RESET}\n"
  printf "  ${CYAN}sudo ${TARGET_BIN} run perf/stall-tracer${RESET}\n"
  printf "  ${CYAN}sudo ${TARGET_BIN} run app/universal-tls-sniffer${RESET}\n"
fi

printf "\n${BOLD}Online Collaborative Incident Response:${RESET}\n"
printf "  Visit ${CYAN}https://eprobe.io/${RESET} to view live web diagnostic dashboards.\n\n"
