#!/usr/bin/env bash
# DataNivra agent installer — single-host Docker Compose + systemd
#
# Usage (run as root or with sudo):
#   curl -fsSL https://www.datanivra.com/install.sh | sudo bash
#
# Options (environment variables):
#   DN_VERSION=0.4.1          pin a specific agent version (default: latest published)
#   DN_SECRETS_DIR=/run/datanivra-secrets   override secrets mount path
#   DN_NO_START=1             install and configure but do not start the service
#
# What this script does:
#   1. Verifies requirements (Linux, Docker ≥ 24, docker compose, curl, sha256sum)
#   2. Creates a system user 'datanivra' (UID 10001, no login shell)
#   3. Downloads the signed release package from https://www.datanivra.com
#   4. Verifies the SHA256 checksum of every downloaded file
#   5. Installs the agent under /opt/datanivra
#   6. Creates a systemd unit that manages the agent container via Docker Compose
#   7. Prompts for your enrollment token (or reads DN_ENROLLMENT_TOKEN from the environment)
#   8. Writes the token to /run/datanivra-secrets/enrollment-token (mode 0600, owner datanivra)
#   9. Enables the unit and starts the agent
#
# After installation the agent calls home over HTTPS (port 443) only.
# No inbound port is opened.  Uninstall: systemctl disable --now datanivra-agent && rm -rf /opt/datanivra
#
# SECURITY: always read a script before piping it to a shell.
# Source: https://www.datanivra.com/install.sh
#         https://github.com/datanivra/datanivra-platform/blob/main/apps/web/public/install.sh

set -euo pipefail

# --------------------------------------------------------------------------- colours + helpers
_RED=''
_GRN=''
_YEL=''
_RST=''
if [[ -t 2 ]]; then
  _GRN='\033[0;32m'
  _YEL='\033[1;33m'
  _RST='\033[0m'
fi

info()  { printf "%b[datanivra]%b %s\n" "$_GRN" "$_RST" "$*" >&2; }
warn()  { printf "%b[datanivra warn]%b %s\n" "$_YEL" "$_RST" "$*" >&2; }
die()   { printf "[datanivra error] %s\n" "$*" >&2; exit 1; }

# --------------------------------------------------------------------------- guard rails
[[ "$(uname -s)" == "Linux" ]] || die "This installer supports Linux only. For other platforms see https://www.datanivra.com/docs/agent-installation"
[[ $EUID -eq 0 ]] || die "Run as root (or prefix with sudo): sudo bash install.sh"

# --------------------------------------------------------------------------- configuration
SITE_URL="https://www.datanivra.com"
INSTALL_DIR="/opt/datanivra"
SECRETS_DIR="${DN_SECRETS_DIR:-/run/datanivra-secrets}"
AGENT_USER="datanivra"
AGENT_UID=10001
SERVICE_NAME="datanivra-agent"

# --------------------------------------------------------------------------- latest version
_resolve_version() {
  local manifest
  manifest=$(curl -fsSL "${SITE_URL}/downloads/agent/releases.json") || die "Could not fetch release manifest from ${SITE_URL}"
  # jq is optional; fall back to python3 if present, else awk
  if command -v jq &>/dev/null; then
    printf '%s' "$manifest" | jq -r '[.releases[] | select(.status == "PUBLISHED")] | last | .version'
  elif command -v python3 &>/dev/null; then
    printf '%s' "$manifest" | python3 -c "
import json,sys
releases = json.load(sys.stdin)['releases']
published = [r for r in releases if r['status'] == 'PUBLISHED']
print(published[-1]['version'])
"
  else
    printf '%s' "$manifest" | awk -F'"' '/"PUBLISHED"/{p=1} p && /"version"/{print $4; exit}'
  fi
}

VERSION="${DN_VERSION:-}"
if [[ -z "$VERSION" ]]; then
  info "Resolving latest published agent version…"
  VERSION=$(_resolve_version)
fi
[[ -n "$VERSION" ]] || die "Could not determine agent version. Set DN_VERSION=<version> to pin one."
info "Installing DataNivra agent ${VERSION}"

# --------------------------------------------------------------------------- check requirements
_require() {
  command -v "$1" &>/dev/null || die "'$1' is required but not found. Install it and retry."
}
_require curl
_require sha256sum

# Docker
_require docker
docker info &>/dev/null || die "Docker daemon is not running. Start it and retry."
DOCKER_VERSION=$(docker version --format '{{.Server.Version}}' 2>/dev/null || echo "0.0.0")
DOCKER_MAJOR=${DOCKER_VERSION%%.*}
(( DOCKER_MAJOR >= 24 )) || warn "Docker ${DOCKER_VERSION} detected; Docker ≥ 24 is recommended."

# docker compose (plugin form preferred; standalone fallback)
if docker compose version &>/dev/null 2>&1; then
  COMPOSE="docker compose"
elif command -v docker-compose &>/dev/null; then
  COMPOSE="docker-compose"
  warn "Using standalone docker-compose. The Docker Compose plugin is preferred."
else
  die "Docker Compose is not installed. Install it (https://docs.docker.com/compose/install/) and retry."
fi
info "Using '${COMPOSE}'"

# --------------------------------------------------------------------------- system user
if ! id -u "$AGENT_USER" &>/dev/null; then
  info "Creating system user '${AGENT_USER}' (UID ${AGENT_UID})"
  useradd \
    --system \
    --no-create-home \
    --shell /sbin/nologin \
    --uid "$AGENT_UID" \
    --comment "DataNivra agent" \
    "$AGENT_USER"
else
  _existing_uid=$(id -u "$AGENT_USER")
  if [[ "$_existing_uid" != "$AGENT_UID" ]]; then
    warn "User '${AGENT_USER}' exists with UID ${_existing_uid} (expected ${AGENT_UID}). Proceeding."
  else
    info "System user '${AGENT_USER}' already exists (UID ${AGENT_UID})"
  fi
fi

# Docker group membership so the agent can call the Docker socket
if getent group docker &>/dev/null; then
  usermod -aG docker "$AGENT_USER" 2>/dev/null || true
fi

# --------------------------------------------------------------------------- download + verify
DOWNLOAD_BASE="${SITE_URL}/downloads/agent/${VERSION}"
PACKAGE="datanivra-agent-docker-compose-${VERSION}.tar.gz"
SUMS_FILE="SHA256SUMS"
WORK_DIR=$(mktemp -d)
trap 'rm -rf "$WORK_DIR"' EXIT

info "Downloading release package…"
curl -fsSL --progress-bar "${DOWNLOAD_BASE}/${PACKAGE}"   -o "${WORK_DIR}/${PACKAGE}"
curl -fsSL              "${DOWNLOAD_BASE}/${SUMS_FILE}" -o "${WORK_DIR}/${SUMS_FILE}"

info "Verifying checksum…"
# SHA256SUMS contains entries for all packages in the release; extract the one we need
grep "${PACKAGE}" "${WORK_DIR}/${SUMS_FILE}" | sha256sum --check --status - \
  2>/dev/null || die "Checksum verification FAILED for ${PACKAGE}. The file may be corrupt or tampered."
info "Checksum OK"

# --------------------------------------------------------------------------- install
info "Installing to ${INSTALL_DIR}…"
mkdir -p "$INSTALL_DIR"
tar -xzf "${WORK_DIR}/${PACKAGE}" -C "$INSTALL_DIR" --strip-components=1

chown -R root:root "$INSTALL_DIR"
# The compose file and docker socket don't need to be writable by the agent user.

# --------------------------------------------------------------------------- secrets directory
# /run is a tmpfs on systemd systems, so we create the directory via tmpfiles.d.
# The mount is preserved across reboots; the token file is persistent on the host
# but projected into the container as read-only.
info "Configuring secrets directory (${SECRETS_DIR})…"
install -d -m 0700 -o "$AGENT_USER" -g "$AGENT_USER" "$SECRETS_DIR"

# Persist across reboots via tmpfiles.d
cat > /etc/tmpfiles.d/datanivra-agent.conf <<TMPFILES
d  ${SECRETS_DIR}  0700  ${AGENT_USER}  ${AGENT_USER}  -
TMPFILES

# --------------------------------------------------------------------------- enrollment token
TOKEN_FILE="${SECRETS_DIR}/enrollment-token"
if [[ -f "$TOKEN_FILE" ]]; then
  info "Enrollment token already exists at ${TOKEN_FILE} — keeping it."
elif [[ -n "${DN_ENROLLMENT_TOKEN:-}" ]]; then
  info "Writing enrollment token from DN_ENROLLMENT_TOKEN…"
  printf '%s' "$DN_ENROLLMENT_TOKEN" | install -m 0600 -o "$AGENT_USER" -g "$AGENT_USER" /dev/stdin "$TOKEN_FILE"
else
  echo
  printf "  Paste your enrollment token (from the DataNivra console → Agents → Install):\n  > "
  read -r _token
  [[ -n "$_token" ]] || die "Enrollment token is required. Re-run and paste the token when prompted."
  printf '%s' "$_token" | install -m 0600 -o "$AGENT_USER" -g "$AGENT_USER" /dev/stdin "$TOKEN_FILE"
fi
info "Enrollment token stored."

# --------------------------------------------------------------------------- systemd unit
info "Writing systemd service…"
cat > "/etc/systemd/system/${SERVICE_NAME}.service" <<UNIT
[Unit]
Description=DataNivra Agent
Documentation=https://www.datanivra.com/docs/agent-installation
After=network-online.target docker.service
Requires=docker.service
StartLimitIntervalSec=120
StartLimitBurst=5

[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=${INSTALL_DIR}
ExecStart=${COMPOSE} up --remove-orphans --wait
ExecStop=${COMPOSE} down
# Forward compose logs to the journal
StandardOutput=journal
StandardError=journal
SyslogIdentifier=datanivra-agent
Restart=on-failure
RestartSec=10s

[Install]
WantedBy=multi-user.target
UNIT

systemctl daemon-reload
systemctl enable "$SERVICE_NAME"

# --------------------------------------------------------------------------- start
if [[ "${DN_NO_START:-0}" == "1" ]]; then
  warn "DN_NO_START=1 — service installed but not started. Run: systemctl start ${SERVICE_NAME}"
else
  info "Starting ${SERVICE_NAME}…"
  systemctl start "$SERVICE_NAME"
  sleep 2
  if systemctl is-active --quiet "$SERVICE_NAME"; then
    info "Agent is running."
  else
    warn "Service may still be starting. Check: journalctl -u ${SERVICE_NAME} -f"
  fi
fi

# --------------------------------------------------------------------------- done
cat >&2 <<DONE

  DataNivra agent ${VERSION} installed successfully.

  Useful commands:
    journalctl -u ${SERVICE_NAME} -f        # live logs
    systemctl status ${SERVICE_NAME}         # service status
    systemctl stop ${SERVICE_NAME}           # stop the agent
    systemctl disable --now ${SERVICE_NAME}  # stop + disable autostart

  Uninstall:
    systemctl disable --now ${SERVICE_NAME}
    rm -rf ${INSTALL_DIR} ${SECRETS_DIR} /etc/systemd/system/${SERVICE_NAME}.service /etc/tmpfiles.d/datanivra-agent.conf

  Docs: https://www.datanivra.com/docs/agent-installation

DONE
