#!/bin/bash
# =============================================================================
# nfs.sh
# Purpose: Install and configure NFS server
# =============================================================================
 
set -euo pipefail
 
# Configuration
EXPORT_DIR="/export/nfs"
NFS_SERVICE="nfs-server"
FIREWALL_SERVICES=("nfs" "mountd" "rpc-bind")
 
# Ensure running as root
if [[ $EUID -ne 0 ]]; then
  echo "This script must be run as root" >&2
  exit 1
fi
 
echo "Installing NFS server..."
 
# Step 1: Update and install nfs-utils
if ! rpm -q nfs-utils >/dev/null 2>&1; then
  dnf update -y
  dnf install -y nfs-utils
fi
 
# Step 2: Create export directory
mkdir -p "$EXPORT_DIR"
 
# Step 3: Ensure permissions
chmod 777 "$EXPORT_DIR"
chown nobody:nobody "$EXPORT_DIR"
 
# Step 4: Configure /etc/exports (only if entry not present)
EXPORT_ENTRY="$EXPORT_DIR *(rw,sync,no_root_squash,no_all_squash,no_subtree_check)"
if ! grep -Fqs "$EXPORT_DIR" /etc/exports; then
  echo "$EXPORT_ENTRY" > /etc/exports
else
  # Ensure correct export line
  grep -v "^$EXPORT_DIR" /etc/exports > /tmp/exports.tmp || true
  echo "$EXPORT_ENTRY" >> /tmp/exports.tmp
  mv /tmp/exports.tmp /etc/exports
fi
 
# Step 5: Reload export configuration
exportfs -rav
 
# Step 6: Enable and start NFS server
if ! systemctl is-enabled "$NFS_SERVICE" >/dev/null 2>&1; then
  systemctl enable "$NFS_SERVICE"
fi
systemctl restart "$NFS_SERVICE"
 
# Step 7: Handle firewalld if active
if systemctl is-active firewalld --quiet; then
  echo "firewalld is active. Adding NFS services to firewall..."
  for service in "${FIREWALL_SERVICES[@]}"; do
    if ! firewall-cmd --state >/dev/null 2>&1; then
      echo "firewalld is not running, starting..."
      systemctl start firewalld
    fi
 
    if ! firewall-cmd --list-services --permanent | grep -wq "$service"; then
      firewall-cmd --permanent --add-service="$service"
    fi
  done
  firewall-cmd --reload
else
  echo "firewalld is not active. Skipping firewall configuration."
fi
 
# Step 8: Get primary IP address
IP_ADDR=$(ip -4 addr show scope global | grep -oP '(?<=inet\s)\d+(\.\d+){3}' | head -1)
if [[ -z "$IP_ADDR" ]]; then
  echo "Failed to detect IP address" >&2
  exit 1
fi
 
# Step 9: Output result
echo
echo "NFS server setup complete"
echo "Server IP: $IP_ADDR"
echo "Export directory: $EXPORT_DIR"
echo "Use in Kubernetes StorageClass:"
echo "  server: $IP_ADDR"
echo "  share: $EXPORT_DIR"
