#!/usr/bin/env bash
# ==============================================================================
# 01-base-node.sh — Hostname, Cluster-Wide UTC, /etc/hosts Mesh & Base Packages
# Implements Manual 19 Traps #13 (UTC timezone) & #17 (remove 127.0.1.1 before 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}"
: "${CLUSTER_HOSTS_B64:?CLUSTER_HOSTS_B64 (base64 hosts table) is required}"

r2a_step 1 4 "Setting hostname (${NODE_HOSTNAME}) and synchronizing cluster-wide UTC clock"
hostnamectl set-hostname "$NODE_HOSTNAME"
r2a_sync_clock

r2a_step 2 4 "Removing 127.0.1.1 and synchronizing cluster /etc/hosts block"
sed -i '/^127\.0\.1\.1/d' /etc/hosts
sed -i '/^# BEGIN RING2ALL CLUSTER HOSTS$/,/^# END RING2ALL CLUSTER HOSTS$/d' /etc/hosts
{
  echo "# BEGIN RING2ALL CLUSTER HOSTS"
  echo "$CLUSTER_HOSTS_B64" | base64 -d
  echo ""
  echo "# END RING2ALL CLUSTER HOSTS"
} >> /etc/hosts

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} resolved to invalid loopback/empty address '${RESOLVED_IP}' instead of ${NODE_IP}."
fi
r2a_ok "Verified ${NODE_HOSTNAME} -> ${RESOLVED_IP}"

r2a_step 3 4 "Installing base Linux utilities, NTP, Python 3, and nftables"
apt-get update -y
apt-get install -y \
  curl wget gnupg2 sudo lsb-release ca-certificates nftables jq systemd-timesyncd vim git python3 openssl

systemctl enable --now systemd-timesyncd 2>/dev/null || true

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
fi

r2a_step 4 4 "Recording node bootstrap metadata"
mkdir -p /etc/softswitch
printf '%s\n' "${NODE_ROLE:-unknown}" > /etc/softswitch/node-role
chmod 644 /etc/softswitch/node-role

r2a_ok "Base node bootstrap complete on ${NODE_HOSTNAME} (${NODE_IP})."
r2a_result "{\"hostname\":\"${NODE_HOSTNAME}\",\"ip\":\"${NODE_IP}\",\"resolved_ip\":\"${RESOLVED_IP}\",\"timezone\":\"UTC\"}"
