#!/usr/bin/env bash
# bootstrap.sh — one-command hive installer.
#
# PRE-REQ: curl (that's it)
#
# USAGE:
#   # Interactive — bootstrap stops so you can edit config, then run hive supervisor yourself
#   curl -fsSL https://raw.githubusercontent.com/kubestellar/hive/main/bin/bootstrap.sh | sudo bash
#
#   # Fully automated — pass config inline, supervisor starts immediately
#   curl -fsSL .../bootstrap.sh | sudo bash -s -- \
#     --repos "owner/repo1 owner/repo2" \
#     --backends "copilot" \
#     --slack "https://hooks.slack.com/services/..." \
#     --start
#
# PARAMETERS (all optional — any not passed leave the template default in place):
#   --repos     "owner/r1 owner/r2"   HIVE_REPOS: space-separated list of GitHub repos to watch
#   --backends  "copilot gemini"       HIVE_BACKENDS: agent CLIs to use (copilot claude gemini goose)
#   --models    "ollama litellm"       HIVE_MODEL_SERVICES: local model stack (optional)
#   --ntfy      "my-topic"             NTFY_TOPIC for ntfy.sh push alerts
#   --slack     "https://hooks..."     SLACK_WEBHOOK for Slack alerts
#   --discord   "https://discord..."   DISCORD_WEBHOOK for Discord alerts
#   --user      "myuser"               AGENT_USER (default: the user who ran sudo)
#   --no-auto-install                  Set HIVE_AUTO_INSTALL=false (skip CLI auto-install)
#   --start                            Run 'hive supervisor' immediately after bootstrap
#
# Three-step setup without --start:
#   Step 1 — this script    → installs git/tmux/jq, clones hive, creates /etc/hive/agent.env
#   Step 2 — you            → sudo $EDITOR /etc/hive/agent.env  (set HIVE_REPOS + notifications)
#   Step 3 — hive supervisor → installs agent CLIs/Node/ollama/bd then starts all agents
#
# With --repos + a notification channel + --start, steps 2 and 3 collapse into one.
set -euo pipefail

HIVE_REPO="https://github.com/kubestellar/hive.git"
HIVE_INSTALL_DIR="/opt/hive"
HIVE_CONF_DIR="/etc/hive"
HIVE_CONF="$HIVE_CONF_DIR/agent.env"
BIN_DIR="/usr/local/bin"

# ── Parameter defaults ────────────────────────────────────────────────────────
ARG_REPOS=""
ARG_BACKENDS=""
ARG_MODELS=""
ARG_NTFY=""
ARG_SLACK=""
ARG_DISCORD=""
ARG_USER=""
ARG_AUTO_INSTALL="true"
ARG_START=0

while [[ $# -gt 0 ]]; do
  case "$1" in
    --repos)           ARG_REPOS="$2";        shift 2 ;;
    --repos=*)         ARG_REPOS="${1#*=}";   shift   ;;
    --backends)        ARG_BACKENDS="$2";     shift 2 ;;
    --backends=*)      ARG_BACKENDS="${1#*=}";shift   ;;
    --models)          ARG_MODELS="$2";       shift 2 ;;
    --models=*)        ARG_MODELS="${1#*=}";  shift   ;;
    --ntfy)            ARG_NTFY="$2";         shift 2 ;;
    --ntfy=*)          ARG_NTFY="${1#*=}";    shift   ;;
    --slack)           ARG_SLACK="$2";        shift 2 ;;
    --slack=*)         ARG_SLACK="${1#*=}";   shift   ;;
    --discord)         ARG_DISCORD="$2";      shift 2 ;;
    --discord=*)       ARG_DISCORD="${1#*=}"; shift   ;;
    --user)            ARG_USER="$2";         shift 2 ;;
    --user=*)          ARG_USER="${1#*=}";    shift   ;;
    --no-auto-install) ARG_AUTO_INSTALL="false"; shift ;;
    --start)           ARG_START=1;           shift   ;;
    -h|--help)
      grep '^#' "$0" | grep -v '#!/' | sed 's/^# \?//'
      exit 0 ;;
    *) echo "Unknown flag: $1  (use --help)" >&2; exit 1 ;;
  esac
done

# ── Colours ──────────────────────────────────────────────────────────────────
RED='\033[0;31m'; GRN='\033[0;32m'; YLW='\033[1;33m'; BLD='\033[1m'; RST='\033[0m'
ok()   { echo -e "${GRN}✓${RST}  $*"; }
info() { echo -e "${BLD}→${RST}  $*"; }
warn() { echo -e "${YLW}⚠${RST}  $*"; }
die()  { echo -e "${RED}✗${RST}  $*" >&2; exit 1; }
hdr()  { echo -e "\n${BLD}── $* ──${RST}"; }

# ── Must run as root ──────────────────────────────────────────────────────────
if [[ "$(id -u)" -ne 0 ]]; then
  die "Run as root:  curl -fsSL ... | sudo bash"
fi

# ── Detect the real user (the one who typed sudo) ─────────────────────────────
REAL_USER="${SUDO_USER:-${USER:-$(logname 2>/dev/null || echo dev)}}"
REAL_HOME="$(getent passwd "$REAL_USER" 2>/dev/null | cut -d: -f6 || echo "/home/$REAL_USER")"

# ── Detect package manager ────────────────────────────────────────────────────
hdr "Detecting package manager"
if   command -v apt-get  &>/dev/null; then PKG_MGR="apt"
elif command -v dnf      &>/dev/null; then PKG_MGR="dnf"
elif command -v yum      &>/dev/null; then PKG_MGR="yum"
elif command -v pacman   &>/dev/null; then PKG_MGR="pacman"
elif command -v brew     &>/dev/null; then PKG_MGR="brew"
else die "No supported package manager found (tried apt/dnf/yum/pacman/brew)"; fi
ok "using $PKG_MGR"

pkg_install() {
  case "$PKG_MGR" in
    apt)    apt-get install -y -qq "$@" >/dev/null ;;
    dnf)    dnf install -y -q "$@" >/dev/null ;;
    yum)    yum install -y -q "$@" >/dev/null ;;
    pacman) pacman -Sy --noconfirm "$@" >/dev/null ;;
    brew)   sudo -u "$REAL_USER" brew install "$@" >/dev/null ;;
  esac
}

pkg_update() {
  case "$PKG_MGR" in
    apt)    apt-get update -qq >/dev/null ;;
    dnf|yum) : ;; # yum/dnf resolve on demand
    pacman) pacman -Sy --noconfirm >/dev/null ;;
    brew)   sudo -u "$REAL_USER" brew update >/dev/null ;;
  esac
}

# ── Install base deps ─────────────────────────────────────────────────────────
hdr "Installing base dependencies"
pkg_update || warn "package index update failed — continuing anyway"
for tool in curl git tmux jq; do
  if command -v "$tool" &>/dev/null; then
    ok "$tool already installed"
  else
    info "Installing $tool..."
    pkg_install "$tool" && ok "$tool installed"
  fi
done

# ── Clone or locate hive repo ─────────────────────────────────────────────────
hdr "Setting up hive repo"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" 2>/dev/null && pwd || true)"
# If we're running from inside an already-cloned repo, use it directly.
if [[ -f "$SCRIPT_DIR/../install.sh" && -f "$SCRIPT_DIR/../bin/hive.sh" ]]; then
  HIVE_INSTALL_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
  ok "using existing repo at $HIVE_INSTALL_DIR"
elif [[ -d "$HIVE_INSTALL_DIR/.git" ]]; then
  info "Updating existing clone at $HIVE_INSTALL_DIR..."
  git -C "$HIVE_INSTALL_DIR" pull --rebase -q && ok "repo updated"
else
  info "Cloning hive to $HIVE_INSTALL_DIR..."
  git clone -q "$HIVE_REPO" "$HIVE_INSTALL_DIR" && ok "cloned"
fi
chown -R "$REAL_USER:$REAL_USER" "$HIVE_INSTALL_DIR" 2>/dev/null || true

# ── Create hive symlink ───────────────────────────────────────────────────────
if [[ ! -f "$BIN_DIR/hive" ]]; then
  install -m 0755 "$HIVE_INSTALL_DIR/bin/hive.sh" "$BIN_DIR/hive"
  ok "hive command installed → $BIN_DIR/hive"
fi

# ── Create default config ─────────────────────────────────────────────────────
hdr "Config"
mkdir -p "$HIVE_CONF_DIR"
if [[ -f "$HIVE_CONF" ]]; then
  ok "$HIVE_CONF already exists — patching with any supplied arguments"
else
  info "Creating default config from template..."
  cp "$HIVE_INSTALL_DIR/config/agent.env.example" "$HIVE_CONF"
fi

# Resolve AGENT_USER: --user arg > sudo caller > fallback
CONF_USER="${ARG_USER:-$REAL_USER}"
CONF_HOME="$(getent passwd "$CONF_USER" 2>/dev/null | cut -d: -f6 || echo "/home/$CONF_USER")"

# Apply baseline defaults (always safe to set)
sed -i \
  -e "s|^AGENT_USER=.*|AGENT_USER=$CONF_USER|" \
  -e "s|^AGENT_WORKDIR=.*|AGENT_WORKDIR=$CONF_HOME|" \
  -e "s|^AGENT_LOG_FILE=.*|AGENT_LOG_FILE=/var/log/hive/agent.log|" \
  -e "s|^AGENT_LAUNCH_CMD=.*|AGENT_LAUNCH_CMD=copilot --allow-all|" \
  -e "s|^HIVE_AUTO_INSTALL=.*|HIVE_AUTO_INSTALL=$ARG_AUTO_INSTALL|" \
  "$HIVE_CONF" 2>/dev/null || true

# Apply CLI arguments (only if the flag was passed)
set_conf() {
  local key="$1" val="$2"
  if grep -q "^${key}=" "$HIVE_CONF"; then
    sed -i "s|^${key}=.*|${key}=${val}|" "$HIVE_CONF"
  else
    echo "${key}=${val}" >> "$HIVE_CONF"
  fi
}

[[ -n "$ARG_REPOS"    ]] && set_conf HIVE_REPOS       "$ARG_REPOS"
[[ -n "$ARG_BACKENDS" ]] && set_conf HIVE_BACKENDS     "$ARG_BACKENDS"
[[ -n "$ARG_MODELS"   ]] && set_conf HIVE_MODEL_SERVICES "$ARG_MODELS"
[[ -n "$ARG_NTFY"     ]] && set_conf NTFY_TOPIC        "$ARG_NTFY"
[[ -n "$ARG_SLACK"    ]] && set_conf SLACK_WEBHOOK     "$ARG_SLACK"
[[ -n "$ARG_DISCORD"  ]] && set_conf DISCORD_WEBHOOK   "$ARG_DISCORD"

# Ensure required vars exist (blank if not set by args)
grep -q '^HIVE_BACKENDS='       "$HIVE_CONF" || echo "HIVE_BACKENDS=copilot"              >> "$HIVE_CONF"
grep -q '^HIVE_REPOS='          "$HIVE_CONF" || echo "HIVE_REPOS="                        >> "$HIVE_CONF"
grep -q '^AGENT_SESSION_NAME='  "$HIVE_CONF" || echo "AGENT_SESSION_NAME=hive"            >> "$HIVE_CONF"
grep -q '^AGENT_LOOP_PROMPT='   "$HIVE_CONF" || echo 'AGENT_LOOP_PROMPT=Run your supervisor pass.' >> "$HIVE_CONF"
ok "$HIVE_CONF configured"

mkdir -p /var/log/hive
chown "$CONF_USER:$CONF_USER" /var/log/hive 2>/dev/null || true

# ── Run install.sh ────────────────────────────────────────────────────────────
hdr "Running install.sh"
bash "$HIVE_INSTALL_DIR/install.sh" && ok "scripts and systemd units installed"

# ── Done ──────────────────────────────────────────────────────────────────────
echo ""
echo -e "${GRN}${BLD}✓ hive bootstrapped successfully!${RST}"
echo ""
echo -e "  ${BLD}Two things left:${RST}"
echo ""
echo -e "  ${YLW}1. Edit your config:${RST}"
echo -e "     sudo \$EDITOR $HIVE_CONF"
echo -e "     # Set at minimum: HIVE_REPOS, and one of NTFY_TOPIC / SLACK_WEBHOOK / DISCORD_WEBHOOK"
echo ""
echo -e "  ${YLW}2. Start everything:${RST}"
echo -e "     hive supervisor"
echo -e "     # Installs missing CLIs (copilot/claude/gemini/goose), then starts all agents"
echo ""
echo -e "  ${BLD}Watch live:${RST}  hive attach supervisor"
echo -e "  ${BLD}Status:${RST}      hive status"
echo ""
