#!/usr/bin/env bash
# ==============================================================================
# 02-nms-agent-snmp.sh — Install SNMPv3 (Random AuthPriv) & Native Node Control API
# Runs on EVERY cluster node during Stage 0 & Day-2 scaling:
#   1. Installs & configures snmpd with per-cluster random SNMPv3 SHA+AES user
#   2. Installs r2a-node-agent.service (HTTPS :9443, random per-node 256-bit token)
#   3. Ensures NMS ED25519 SSH key is pinned for passwordless access
# ==============================================================================
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib/common.sh
source "${SCRIPT_DIR}/lib/common.sh"

r2a_load_env
r2a_require_root
r2a_require_debian13

: "${SNMP_USER:?SNMP_USER is required}"
: "${SNMP_AUTH_PASS:?SNMP_AUTH_PASS is required}"
: "${SNMP_PRIV_PASS:?SNMP_PRIV_PASS is required}"
: "${NMS_NODE_TOKEN:?NMS_NODE_TOKEN is required}"
NODE_ROLE="${NODE_ROLE:-unknown}"
NMS_SSH_PUBLIC_KEY="${NMS_SSH_PUBLIC_KEY:-}"
NMS_AGENT_PORT="${NMS_AGENT_PORT:-9443}"

r2a_step 1 4 "Pinning Ring2All NMS ED25519 SSH public key for passwordless management"
if [[ -n "$NMS_SSH_PUBLIC_KEY" ]]; then
  mkdir -p /root/.ssh
  chmod 700 /root/.ssh
  touch /root/.ssh/authorized_keys
  chmod 600 /root/.ssh/authorized_keys
  if ! grep -Fq "$NMS_SSH_PUBLIC_KEY" /root/.ssh/authorized_keys; then
    printf '%s\n' "$NMS_SSH_PUBLIC_KEY" >> /root/.ssh/authorized_keys
  fi
  r2a_ok "NMS ED25519 public key pinned in /root/.ssh/authorized_keys."
fi

r2a_step 2 4 "Installing and configuring SNMPv3 (authPriv SHA/AES) daemon"
apt-get update -y
apt-get install -y snmpd snmp openssl python3

systemctl stop snmpd 2>/dev/null || true
sed -i "/usmUser.*${SNMP_USER}/d" /var/lib/snmp/snmpd.conf 2>/dev/null || true
sed -i "/^createUser ${SNMP_USER} /d" /var/lib/snmp/snmpd.conf 2>/dev/null || true
echo "createUser ${SNMP_USER} SHA \"${SNMP_AUTH_PASS}\" AES \"${SNMP_PRIV_PASS}\"" >> /var/lib/snmp/snmpd.conf

cat << EOF > /etc/snmp/snmpd.conf
agentAddress udp:161
rouser ${SNMP_USER} priv
includeAllDisks 10%
sysLocation Ring2All Horizontal Cluster (${NODE_ROLE})
sysContact noc@ring2all.local
EOF

systemctl enable --now snmpd
sleep 1
if snmpget -v3 -u "$SNMP_USER" -l authPriv -a SHA -A "$SNMP_AUTH_PASS" -x AES -X "$SNMP_PRIV_PASS" 127.0.0.1 1.3.6.1.2.1.1.1.0 >/dev/null 2>&1; then
  r2a_ok "SNMPv3 authPriv local probe verified (user=${SNMP_USER})."
else
  r2a_warn "SNMPv3 local probe returned non-zero; check snmpd logs."
fi

r2a_step 3 4 "Deploying native Ring2All Node Control API (r2a-node-agent HTTPS :${NMS_AGENT_PORT})"
mkdir -p /etc/softswitch /usr/local/lib/ring2all-nms-agent
AGENT_SRC="${SCRIPT_DIR}/lib/r2a-node-agent.py"
[[ -f "$AGENT_SRC" ]] || r2a_fail "Missing ${AGENT_SRC}"
install -m 755 "$AGENT_SRC" /usr/local/lib/ring2all-nms-agent/r2a-node-agent.py

if [[ ! -f /etc/softswitch/nms-agent.crt || ! -f /etc/softswitch/nms-agent.key ]]; then
  openssl req -x509 -nodes -days 3650 -newkey rsa:2048 \
    -keyout /etc/softswitch/nms-agent.key \
    -out /etc/softswitch/nms-agent.crt \
    -subj "/CN=${NODE_HOSTNAME:-ring2all-node}/O=Ring2All NMS Agent" 2>/dev/null
  chmod 600 /etc/softswitch/nms-agent.key
  chmod 644 /etc/softswitch/nms-agent.crt
fi

cat << EOF > /etc/softswitch/nms-agent.env
NMS_AGENT_BIND=0.0.0.0
NMS_AGENT_PORT=${NMS_AGENT_PORT}
NODE_ROLE=${NODE_ROLE}
NMS_NODE_TOKEN=${NMS_NODE_TOKEN}
NMS_AGENT_CERT=/etc/softswitch/nms-agent.crt
NMS_AGENT_KEY=/etc/softswitch/nms-agent.key
EOF
chmod 600 /etc/softswitch/nms-agent.env

cat << 'EOF' > /etc/systemd/system/r2a-node-agent.service
[Unit]
Description=Ring2All NMS Native Node Control Agent (HTTPS)
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
EnvironmentFile=/etc/softswitch/nms-agent.env
ExecStart=/usr/bin/python3 /usr/local/lib/ring2all-nms-agent/r2a-node-agent.py
Restart=always
RestartSec=3
NoNewPrivileges=no

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable --now r2a-node-agent
systemctl restart r2a-node-agent

r2a_step 4 4 "Verifying r2a-node-agent HTTPS /health with constant-time node token"
sleep 1
CODE="$(curl -sk -o /dev/null -w '%{http_code}' -H "X-NMS-Node-Token: ${NMS_NODE_TOKEN}" "https://127.0.0.1:${NMS_AGENT_PORT}/health" || echo 000)"
if [[ "$CODE" != "200" ]]; then
  journalctl -u r2a-node-agent -n 25 --no-pager || true
  r2a_fail "r2a-node-agent /health check failed (HTTP ${CODE})."
fi

r2a_ok "SNMPv3 + r2a-node-agent (HTTPS :${NMS_AGENT_PORT}) active on ${NODE_HOSTNAME}."
r2a_result "{\"snmp_v3\":\"ok\",\"snmp_user\":\"${SNMP_USER}\",\"agent_port\":${NMS_AGENT_PORT},\"agent_status\":\"ok\"}"
