#!/usr/bin/env bash
# Netscope Agent install script
# Source: https://www.netscope.fr/agent/install.sh
# Review before running: https://www.netscope.fr/agent/install.sh
set -euo pipefail

MANIFEST_URL="https://www.netscope.fr/releases/latest.json"
BINARY="netscope-agent"
INSTALL_DIR="/usr/local/bin"
SERVICE_DIR="/etc/systemd/system"

# Detect OS
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
case "$OS" in
  linux|darwin) ;;
  *) echo "Unsupported OS: $OS" >&2; exit 1 ;;
esac

# Detect architecture
ARCH=$(uname -m)
case "$ARCH" in
  x86_64)        ARCH="amd64" ;;
  aarch64|arm64) ARCH="arm64" ;;
  *) echo "Unsupported architecture: $ARCH" >&2; exit 1 ;;
esac

# Fetch release manifest
echo "Fetching latest release info..."
MANIFEST=$(curl -fsSL "$MANIFEST_URL")

if [ -z "$MANIFEST" ]; then
  echo "Failed to fetch release manifest from ${MANIFEST_URL}" >&2
  exit 1
fi

VERSION=$(echo "$MANIFEST" | grep '"version"' | head -1 | cut -d'"' -f4)
if [ -z "$VERSION" ]; then
  echo "Could not parse version from manifest." >&2
  exit 1
fi

echo "Installing Netscope Agent ${VERSION} (${OS}/${ARCH})..."

# Map OS to release naming convention (darwin → macos)
RELEASE_OS="$OS"
[ "$OS" = "darwin" ] && RELEASE_OS="macos"

ARCHIVE="${BINARY}_${VERSION}_${RELEASE_OS}_${ARCH}.tar.gz"
# Extract base URL from first asset's browser_download_url (strip filename)
BASE_URL=$(echo "$MANIFEST" | grep '"browser_download_url"' | head -1 | cut -d'"' -f4 | sed 's|/[^/]*$||')

if [ -z "$BASE_URL" ]; then
  echo "Could not determine download base URL from manifest." >&2
  exit 1
fi

TMPDIR=$(mktemp -d)
trap 'rm -rf "$TMPDIR"' EXIT

# Download archive
curl -fsSL --progress-bar "${BASE_URL}/${ARCHIVE}" -o "${TMPDIR}/${ARCHIVE}"

# Verify SHA-256 checksum from manifest
EXPECTED=$(echo "$MANIFEST" | python3 -c "
import sys, json
data = json.load(sys.stdin)
cs = data.get('checksums', {})
print(cs.get('${ARCHIVE}', ''))
" 2>/dev/null || true)

if [ -z "$EXPECTED" ]; then
  echo "Checksum not found in manifest for ${ARCHIVE}" >&2
  exit 1
fi

if command -v sha256sum >/dev/null 2>&1; then
  ACTUAL=$(sha256sum "${TMPDIR}/${ARCHIVE}" | awk '{print $1}')
elif command -v shasum >/dev/null 2>&1; then
  ACTUAL=$(shasum -a 256 "${TMPDIR}/${ARCHIVE}" | awk '{print $1}')
else
  echo "  Warning: sha256sum/shasum not found, skipping checksum verification"
  ACTUAL="$EXPECTED"
fi

if [ "$ACTUAL" != "$EXPECTED" ]; then
  echo "Checksum mismatch for ${ARCHIVE}!" >&2
  echo "  Expected: ${EXPECTED}" >&2
  echo "  Got:      ${ACTUAL}" >&2
  exit 1
fi
echo "  Checksum verified (SHA-256 OK)"

# Extract and install binary
tar -xzf "${TMPDIR}/${ARCHIVE}" -C "$TMPDIR"
install -m 755 "${TMPDIR}/${BINARY}" "${INSTALL_DIR}/${BINARY}"
echo "  Installed ${INSTALL_DIR}/${BINARY}"

if [ "$OS" = "linux" ]; then
  # Grant cap_net_raw so the agent can send raw ICMP without running as root
  if command -v setcap >/dev/null 2>&1; then
    setcap cap_net_raw+ep "${INSTALL_DIR}/${BINARY}"
    echo "  Capabilities set (cap_net_raw)"
  else
    echo "  Warning: setcap not found. The agent may require sudo to run."
  fi

  # Install systemd service if available
  if command -v systemctl >/dev/null 2>&1; then
    cat > "${SERVICE_DIR}/netscope-agent.service" << 'SYSTEMD'
[Unit]
Description=Netscope Agent
Documentation=https://netscope.fr/agent
After=network-online.target
Wants=network-online.target

[Service]
ExecStart=/usr/local/bin/netscope-agent run
Restart=on-failure
RestartSec=10
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
SYSTEMD
    systemctl daemon-reload
    echo "  Systemd service installed"
  fi
fi

echo ""
echo "Netscope Agent ${VERSION} installed successfully."
echo ""
echo "Next steps:"
echo "  1. Generate a config file:  sudo ${BINARY} config"
echo "  2. Edit the config:         sudo nano /etc/netscope-agent/config.yaml"
echo "     (set your API key and project ID from dashboard.netscope.fr)"
if [ "$OS" = "linux" ] && command -v systemctl >/dev/null 2>&1; then
  echo "  3. Start the service:       sudo systemctl enable --now netscope-agent"
else
  echo "  3. Run the agent:           sudo ${BINARY} run"
fi
echo ""
echo "Get your API key at: https://www.netscope.fr/register"
