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

if [[ "${EUID}" -ne 0 ]]; then
  echo "Please run as root or with sudo."
  exit 1
fi

export DEBIAN_FRONTEND=noninteractive

apt-get update
apt-get install -y \
  apt-transport-https \
  bat \
  build-essential \
  ca-certificates \
  curl \
  fail2ban \
  fzf \
  gh \
  git \
  gnupg \
  jq \
  nginx \
  nodejs \
  npm \
  pipx \
  postgresql-client \
  python3 \
  python3-pip \
  redis-tools \
  ripgrep \
  software-properties-common \
  tmux \
  ufw \
  unattended-upgrades \
  zsh

apt-get install -y eza || true

if ! command -v docker >/dev/null 2>&1; then
  install -m 0755 -d /etc/apt/keyrings
  . /etc/os-release
  if [[ "${ID}" != "ubuntu" && "${ID}" != "debian" ]]; then
    echo "Docker auto-install supports Ubuntu and Debian hosts. Detected: ${ID}"
    exit 1
  fi
  curl -fsSL "https://download.docker.com/linux/${ID}/gpg" | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
  chmod a+r /etc/apt/keyrings/docker.gpg
  echo \
    "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/${ID} ${VERSION_CODENAME} stable" \
    >/etc/apt/sources.list.d/docker.list
  apt-get update
  apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
fi

if ! command -v uv >/dev/null 2>&1; then
  curl -LsSf https://astral.sh/uv/install.sh | sh
fi

if ! command -v pnpm >/dev/null 2>&1; then
  npm install -g pnpm
fi

if ! command -v poetry >/dev/null 2>&1; then
  pipx install poetry
fi

mkdir -p /opt/athena /workspace/projects /workspace/agents /workspace/sandbox /workspace/archives

echo "AthenaOS core tooling installed."
