#!/usr/bin/env bash
# Dual‑stack IP + Gateway config with colour output, reboot/service‑restart menu & hard‑stop safeguard
# Authors : Scott B, Jaydon T - F2H
# Date: 25/08/2025
# Version: 1.2 (fixes unbound gw_v4/gw_v6 on single‑stack runs)

# --- CRLF to LF self‑clean ---
if grep -q $'\r' "$0"; then
    exec bash <(tr -d '\r' < "$0") "$@"
fi

set -euo pipefail

# --- Predeclare to satisfy set -u ---
gw_v4=""
gw_v6=""

# --- OS check: require RHEL family ---
if ! [ -f /etc/redhat-release ]; then
    echo "❌ This script is for RHEL‑family systems only (RHEL, CentOS, Rocky, Alma…)."
    echo "💡 Use the multi‑OS version for Debian/Ubuntu or other distributions."
    exit 1
fi

# --- Colours ---
RED="\033[0;31m"; GREEN="\033[0;32m"; YELLOW="\033[1;33m"
MAGENTA="\033[1;35m"; CYAN="\033[0;36m"; BOLD="\033[1m"; RESET="\033[0m"

validate_ipv4() { [[ $1 =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}/([0-9]|[1-2][0-9]|3[0-2])$ ]]; }
validate_ipv6() { [[ $1 =~ ^([0-9a-fA-F:]+:+)+[0-9a-fA-F]+/([0-9]|[1-9][0-9]|1[0-1][0-9]|12[0-8])$ ]]; }

# --- Reboot reminder check & menu ---
pkg_ver=$(rpm -q --qf "%{VERSION}-%{RELEASE}" NetworkManager 2>/dev/null)
daemon_ver=$(NetworkManager --version 2>/dev/null | awk 'NR==1 {print $1}')

pkg_ver_base=$(echo "$pkg_ver" | sed 's/-.*//')
daemon_ver_base=$(echo "$daemon_ver" | sed 's/-.*//')

if [ -n "$pkg_ver_base" ] && [ -n "$daemon_ver_base" ] && [ "$pkg_ver_base" != "$daemon_ver_base" ]; then
    echo -e "${RED}🚫 Running NetworkManager ($daemon_ver) doesn't match installed package ($pkg_ver)${RESET}"
    echo -e "${YELLOW}💡 This usually means a reboot or NetworkManager restart is required.${RESET}\n"

    echo -e "${BOLD}Options:${RESET}"
    echo "  1) Reboot server"
    echo "  2) Restart NetworkManager"
    echo "  3) Skip and exit"
    read -rp "Choose [1-3]: " choice

    case "$choice" in
        1)  echo -e "${MAGENTA}🔄 Rebooting in 5 seconds... Press Ctrl+C to cancel.${RESET}"
            sleep 5; sudo reboot ;;
        2)  echo -e "${MAGENTA}🔄 Restarting NetworkManager...${RESET}"
            sudo systemctl restart NetworkManager ;;
        *)  echo -e "${CYAN}⏭ Skipping action. Please resolve before running again.${RESET}" ;;
    esac
    exit 1
fi

# --- Version check ---
nmcli_ver=$(nmcli --version | awk 'NR==1 {print $NF}' | sed 's/^version[[:space:]]*//I;s/-.*//')
if [ -n "$nmcli_ver" ] && [ -n "$daemon_ver_base" ]; then
    if [ "$nmcli_ver" != "$daemon_ver_base" ]; then
        echo -e "${YELLOW}⚠ Version mismatch detected:${RESET}"
        echo -e "  nmcli:          ${BOLD}$nmcli_ver${RESET}"
        echo -e "  NetworkManager: ${BOLD}$daemon_ver${RESET}"
    else
        echo -e "${GREEN}✓ nmcli and NetworkManager versions match ($nmcli_ver)${RESET}\n"
    fi
fi

# --- Prompt for IPs ---
read -rp "Enter IP addresses to configure (space-separated, CIDR notation): " ip_list
has_v4=false; has_v6=false
for ip in $ip_list; do
    if validate_ipv4 "$ip"; then has_v4=true
    elif validate_ipv6 "$ip"; then has_v6=true
    else echo -e "${RED}❌ Invalid IP format: $ip${RESET}"; exit 1; fi
done

# --- Prompt for gateways ---
if $has_v4; then
    read -rp "Enter IPv4 Gateway: " gw_v4
    if ! validate_ipv4 "$gw_v4/32"; then echo -e "${RED}❌ Invalid IPv4 gateway: $gw_v4${RESET}"; exit 1; fi
fi
if $has_v6; then
    read -rp "Enter IPv6 Gateway: " gw_v6
    if ! validate_ipv6 "$gw_v6/128"; then echo -e "${RED}❌ Invalid IPv6 gateway: $gw_v6${RESET}"; exit 1; fi
fi

# --- Detect active connection ---
conn_name=$(nmcli -t -f NAME,DEVICE connection show --active | head -n1 | cut -d: -f1)
if [ -z "$conn_name" ]; then echo -e "${RED}❌ No active NetworkManager connection found.${RESET}"; exit 1; fi
echo -e "Using connection: ${BOLD}$conn_name${RESET}"

# --- Apply IPs ---
for ip in $ip_list; do
    if validate_ipv4 "$ip"; then
        echo -e "${GREEN}➕ Adding IPv4${RESET} $ip"
        nmcli connection modify "$conn_name" +ipv4.addresses "$ip" ipv4.method manual
    elif validate_ipv6 "$ip"; then
        echo -e "${CYAN}➕ Adding IPv6${RESET} $ip"
        nmcli connection modify "$conn_name" +ipv6.addresses "$ip" ipv6.method manual
    fi
done

# --- Apply gateways (safe expansion) ---
[ -n "${gw_v4:-}" ] && nmcli connection modify "$conn_name" ipv4.gateway "$gw_v4"
[ -n "${gw_v6:-}" ] && nmcli connection modify "$conn_name" ipv6.gateway "$gw_v6"

# --- Restart connection ---
nmcli connection down "$conn_name" && nmcli connection up "$conn_name"

# --- Report ---
echo
echo -e "${BOLD}${MAGENTA}==================== 📡 Network Configuration Report ====================${RESET}"
printf "%-20s %-50s\n" "Interface:" "$(nmcli -t -f DEVICE connection show --active | head -n1)"
echo -e "${YELLOW}-------------------------------------------------------------------------${RESET}"
echo -e "${BOLD}Configured IP addresses:${RESET}"
ip -o addr show | awk '{print $2, $4}' | column -t
echo -e "${YELLOW}-------------------------------------------------------------------------${RESET}"
echo -e "${BOLD}Gateways (from routing table):${RESET}"
ip route show | grep '^default' | column -t
ip -6 route show | grep '^default' | column -t
echo -e "${YELLOW}-------------------------------------------------------------------------${RESET}"
echo -e "${BOLD}Routing table summary:${RESET}"
echo -e "${CYAN}--- IPv4 ---${RESET}"
ip route show | column -t
echo -e "${CYAN}--- IPv6 ---${RESET}"
ip -6 route show | column -t
echo -e "${BOLD}${MAGENTA}=========================================================================${RESET}"

