#!/bin/bash
# karuhun agent installer — DEV
# Usage: curl -fsSL http://10.99.88.19:8888/install.sh | sudo bash -s -- --key <host_key>
set -euo pipefail

CONTROL_PLANE="10.99.88.19:50052"
BINARY_URL="http://10.99.88.19:8888/karuhun"
NERDCTL_VERSION="2.0.4"
CONTAINERD_VERSION="1.7.24"
RUNC_VERSION="1.1.12"

# ── parse args ────────────────────────────────────────────────────────────────
KEY=""
while [[ $# -gt 0 ]]; do
  case "$1" in
    --key) KEY="$2"; shift 2 ;;
    --key=*) KEY="${1#*=}"; shift ;;
    *) shift ;;
  esac
done

if [[ -z "$KEY" ]]; then
  echo "Usage: $0 --key <host_key>"
  exit 1
fi

ARCH=$(uname -m)
case "$ARCH" in
  x86_64)  ARCH_TAG="amd64" ;;
  aarch64) ARCH_TAG="arm64" ;;
  *) echo "Unsupported arch: $ARCH"; exit 1 ;;
esac

log() { echo -e "\033[1;32m==>\033[0m $*"; }
err() { echo -e "\033[1;31m[ERROR]\033[0m $*" >&2; exit 1; }

[[ $EUID -ne 0 ]] && err "Run as root (sudo bash)"

# ── detect OS ─────────────────────────────────────────────────────────────────
if command -v apt-get &>/dev/null; then
  PKG_MGR="apt"
elif command -v yum &>/dev/null; then
  PKG_MGR="yum"
else
  err "Unsupported package manager (need apt or yum)"
fi

# ── 1. WireGuard ──────────────────────────────────────────────────────────────
if ! command -v wg &>/dev/null; then
  log "Installing WireGuard..."
  if [[ "$PKG_MGR" == "apt" ]]; then
    apt-get update -qq
    apt-get install -y -qq wireguard-tools
  else
    yum install -y wireguard-tools
  fi
else
  log "WireGuard already installed"
fi

# ── 2. containerd ─────────────────────────────────────────────────────────────
if ! command -v containerd &>/dev/null; then
  log "Installing containerd ${CONTAINERD_VERSION}..."
  curl -fsSL "https://github.com/containerd/containerd/releases/download/v${CONTAINERD_VERSION}/containerd-${CONTAINERD_VERSION}-linux-${ARCH_TAG}.tar.gz" \
    | tar -xz -C /usr/local

  # systemd service
  curl -fsSL "https://raw.githubusercontent.com/containerd/containerd/main/containerd.service" \
    -o /etc/systemd/system/containerd.service

  # default config
  mkdir -p /etc/containerd
  containerd config default > /etc/containerd/config.toml
  # use native snapshotter (works in VMs without overlay support)
  sed -i 's/snapshotter = "overlayfs"/snapshotter = "native"/' /etc/containerd/config.toml

  systemctl daemon-reload
  systemctl enable --now containerd
  log "containerd installed and running"
else
  log "containerd already installed"
fi

# ── 3. runc (OCI runtime required by containerd) ─────────────────────────────
if ! command -v runc &>/dev/null; then
  log "Installing runc ${RUNC_VERSION}..."
  curl -fsSL "https://github.com/opencontainers/runc/releases/download/v${RUNC_VERSION}/runc.${ARCH_TAG}" \
    -o /usr/local/sbin/runc
  chmod +x /usr/local/sbin/runc
  log "runc installed"
else
  log "runc already installed"
fi

# ── 4. CNI plugins (needed by nerdctl) ───────────────────────────────────────
if [[ ! -d /opt/cni/bin ]]; then
  log "Installing CNI plugins..."
  CNI_VERSION="1.5.1"
  mkdir -p /opt/cni/bin
  curl -fsSL "https://github.com/containernetworking/plugins/releases/download/v${CNI_VERSION}/cni-plugins-linux-${ARCH_TAG}-v${CNI_VERSION}.tgz" \
    | tar -xz -C /opt/cni/bin
fi

# ── 5. nerdctl ────────────────────────────────────────────────────────────────
if ! command -v nerdctl &>/dev/null; then
  log "Installing nerdctl ${NERDCTL_VERSION}..."
  curl -fsSL "https://github.com/containerd/nerdctl/releases/download/v${NERDCTL_VERSION}/nerdctl-${NERDCTL_VERSION}-linux-${ARCH_TAG}.tar.gz" \
    | tar -xz -C /usr/local/bin nerdctl
  log "nerdctl installed"
else
  log "nerdctl already installed"
fi

# ── 6. karuhun binary ─────────────────────────────────────────────────
log "Downloading karuhun..."
curl -fsSL "$BINARY_URL" -o /usr/local/bin/karuhun
chmod +x /usr/local/bin/karuhun

# ── 7. Register (sets up WireGuard peer + writes /etc/karuhun/agent.conf) ───
log "Registering with control plane..."
karuhun register --key "$KEY" --endpoint "$CONTROL_PLANE"

# ── 8. Install systemd service ────────────────────────────────────────────────
log "Installing karuhun service..."
cat > /etc/systemd/system/karuhun.service << 'UNIT'
[Unit]
Description=Nawahost Agent
After=network.target containerd.service

[Service]
ExecStart=/usr/local/bin/karuhun run
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
UNIT

systemctl daemon-reload
systemctl enable --now karuhun

log "Done! Agent is running."
log "Check status: systemctl status karuhun"
log "View logs:   journalctl -u karuhun -f"
