#!/usr/bin/env bash
# ==============================================================================
# 20-gluster-node.sh — Phase 2: GlusterFS Replica 3 Storage Node Setup
# Implements Manual 19 Trap #17 (strict hostname check before starting glusterd).
# ==============================================================================
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

: "${NODE_HOSTNAME:?NODE_HOSTNAME is required}"
: "${NODE_IP:?NODE_IP is required}"
: "${FS_NODE_IPS:?FS_NODE_IPS (comma-separated) is required}"
: "${CLUSTER_SUBNET:?CLUSTER_SUBNET is required}"
BRICK_ROOT="${GLUSTER_BRICK_ROOT:-/gluster/brick1}"

r2a_step 1 4 "Validating clean hostname resolution before installing glusterfs-server"
RESOLVED_IP="$(getent hosts "$NODE_HOSTNAME" | awk '{print $1}' | head -n 1 || true)"
if [[ -z "$RESOLVED_IP" || "$RESOLVED_IP" == 127.* ]]; then
  r2a_fail "Hostname ${NODE_HOSTNAME} resolves to '${RESOLVED_IP}' (loopback). Run Stage 0 first."
fi

r2a_step 2 4 "Installing glusterfs-server and nftables"
r2a_sync_clock
apt-get update -y
apt-get install -y glusterfs-server nftables

r2a_step 3 4 "Applying Storage Plane firewall rules (nftables + NMS SNMPv3/Agent)"
FS_SET_NFT="$(echo "$FS_NODE_IPS" | sed 's/,/, /g')"
NMS_SRC="${NMS_SERVER_IP:-$CLUSTER_SUBNET}"
cat << EOF > /etc/nftables.conf
#!/usr/sbin/nft -f

flush ruleset

table inet filter {
    chain input {
        type filter hook input priority 0; policy drop;

        iif "lo" accept
        ct state established,related accept
        ct state invalid drop

        tcp dport 22 accept
        ip protocol icmp accept

        # Ring2All NMS SNMPv3 (161/udp) & Native Node Control API (9443/tcp)
        ip saddr ${NMS_SRC} udp dport 161 accept
        ip saddr ${NMS_SRC} tcp dport 9443 accept

        # Full intra-cluster storage traffic
        ip saddr { ${FS_SET_NFT} } accept

        # Client FUSE mounts from Ring2All cluster subnet
        ip saddr ${CLUSTER_SUBNET} tcp dport { 24007, 24008, 49152-65535 } accept
    }
    chain forward { type filter hook forward priority 0; policy drop; }
    chain output  { type filter hook output priority 0; policy accept; }
}
EOF
systemctl enable --now nftables
nft -f /etc/nftables.conf

r2a_step 4 4 "Creating brick directories and starting glusterd"
mkdir -p "${BRICK_ROOT}/ss-recordings" "${BRICK_ROOT}/ss-uploads" "${BRICK_ROOT}/ss-music"
systemctl enable --now glusterd
systemctl restart glusterd
r2a_wait_for_tcp "127.0.0.1" 24007 30 || r2a_fail "glusterd did not open port 24007."

r2a_ok "GlusterFS storage node ready on ${NODE_HOSTNAME} (${NODE_IP})."
r2a_result "{\"node\":\"${NODE_HOSTNAME}\",\"ip\":\"${NODE_IP}\",\"brick_root\":\"${BRICK_ROOT}\"}"
