#!/bin/sh
set -eu

AUTH_FILE="/etc/freeradius/mods-config/files/authorize"

# Start FreeRADIUS in foreground
# Start in debug/foreground mode for logs
freeradius -X &
PID=$!

prev_mtime=""

poll_reload() {
  while true; do
    if [ -f "$AUTH_FILE" ]; then
      mtime=$(stat -c %Y "$AUTH_FILE" 2>/dev/null || stat -f %m "$AUTH_FILE" 2>/dev/null || echo "")
      if [ "${mtime}" != "${prev_mtime}" ] && [ -n "$mtime" ]; then
        # File changed: send HUP to reload users
        kill -HUP "$PID" 2>/dev/null || true
        prev_mtime="$mtime"
      fi
    fi
    sleep 2
  done
}

poll_reload &

wait "$PID"
