#!/bin/bash
set -euo pipefail
# Safe writer for FreeRADIUS clients.conf (invoked via sudo from the dashboard).
TARGET="${1:-}"
case "${TARGET}" in
  /etc/freeradius/3.0/clients.conf|/etc/freeradius/clients.conf|/etc/raddb/clients.conf)
    ;;
  *)
    echo "Refusing to write: ${TARGET}" >&2
    exit 1
    ;;
esac

umask 027
cat > "${TARGET}"
if getent passwd freerad >/dev/null 2>&1; then
  chown freerad:www-data "${TARGET}" 2>/dev/null || chown root:www-data "${TARGET}"
else
  chown root:www-data "${TARGET}"
fi
chmod 660 "${TARGET}"
if command -v setfacl >/dev/null 2>&1; then
  setfacl -m u:www-data:rw "${TARGET}" 2>/dev/null || true
fi
exit 0
