#!/bin/bash

set -u

value="${wizard_lan_port:-}"
target="${TRIM_PKGETC}/lan_port"

port_changed="0"
if [ -z "$value" ]; then
  if [ -f "$target" ]; then
    rm -f "$target"
    port_changed="1"
  fi
else
  case "$value" in
    *[!0-9]*)
      echo "局域网端口只能包含数字。" > "${TRIM_TEMP_LOGFILE:-/dev/null}"
      exit 1
      ;;
  esac

  if [ "$value" -lt 1024 ] || [ "$value" -gt 65535 ]; then
    echo "局域网端口必须在 1024 到 65535 之间。" > "${TRIM_TEMP_LOGFILE:-/dev/null}"
    exit 1
  fi

  old_port=""
  if [ -f "$target" ]; then
    old_port="$(tr -d '[:space:]' < "$target" 2>/dev/null || true)"
  fi
  if [ "$old_port" != "$value" ]; then
    port_changed="1"
  fi

  mkdir -p "$TRIM_PKGETC"
  umask 077
  printf '%s\n' "$value" > "$target"
fi

SNAPSHOT="${TRIM_PKGVAR}/authorized_paths.snapshot"
CURRENT="${TRIM_DATA_ACCESSIBLE_PATHS:-}"
paths_changed="0"
if [ -f "$SNAPSHOT" ]; then
  PREVIOUS="$(tr -d '[:space:]' < "$SNAPSHOT" 2>/dev/null || true)"
  CURRENT_NORMALIZED="$(printf '%s' "$CURRENT" | tr -d '[:space:]')"
  if [ "$CURRENT_NORMALIZED" != "$PREVIOUS" ]; then
    paths_changed="1"
  fi
else
  if [ -n "$CURRENT" ]; then
    paths_changed="1"
  fi
fi
printf '%s\n' "$CURRENT" > "$SNAPSHOT"

# If LAN port changed, we must restart to re-bind the listen socket
if [ "$port_changed" = "1" ]; then
  main_script="${BASH_SOURCE[0]%/*}/main"
  if [ -x "$main_script" ]; then
    if "$main_script" status >/dev/null 2>&1; then
      "$main_script" stop >> "${TRIM_PKGVAR}/lyranest.log" 2>&1 || true
      "$main_script" start >> "${TRIM_PKGVAR}/lyranest.log" 2>&1 || true
    fi
  fi
elif [ "$paths_changed" = "1" ]; then
  # Authorized paths change: zero-downtime hot reload via SIGHUP
  server_pid_file="${TRIM_PKGVAR}/lyranest-server.pid"
  if [ -f "$server_pid_file" ]; then
    server_pid="$(tr -d '[:space:]' < "$server_pid_file" 2>/dev/null || true)"
    if [ -n "$server_pid" ] && kill -0 "$server_pid" 2>/dev/null; then
      echo "$(date '+%Y-%m-%d %H:%M:%S') Notifying LyraNest server of updated authorized paths via SIGHUP (pid ${server_pid})" >> "${TRIM_PKGVAR}/lyranest.log"
      kill -HUP "$server_pid" 2>/dev/null || true
    fi
  fi
fi

exit 0
