#!/bin/bash
set -u

# Pin PATH rather than rely on sudoers secure_path being set.
PATH=/usr/sbin:/usr/bin:/sbin:/bin
export PATH

usage() {
  echo "usage: unifi-protect-switch-cli apply|get port all|get arl" >&2
  exit 1
}

case "${1:-}" in
  apply)
    [ $# -eq 1 ] || usage
    # Config arrives on stdin and is staged in a root-owned directory, keeping the basename
    # rtl8370-ctl expects.
    dir=$(mktemp -d -p /run switch-config.XXXXXX) || { echo "unifi-protect-switch-cli: failed to create a working directory under /run" >&2; exit 1; }
    tmp="$dir/switch-config.json"
    trap 'rm -rf "$dir"' EXIT
    max_bytes=262144
    # Bound the read too: the unprivileged caller cannot signal this process, so a peer that opens
    # the pipe and never writes would otherwise block here forever.
    /usr/bin/timeout -k 3 15 head -c $((max_bytes + 1)) > "$tmp" || { echo "unifi-protect-switch-cli: failed to read config from stdin" >&2; exit 1; }
    # Refuse an empty or over-cap config rather than truncating it: a partial port config can drop
    # the console's own ports. Reading one byte past the cap is what makes over-cap detectable.
    [ -s "$tmp" ] || { echo "unifi-protect-switch-cli: empty config on stdin" >&2; exit 1; }
    [ "$(wc -c < "$tmp")" -le "$max_bytes" ] || { echo "unifi-protect-switch-cli: config on stdin exceeds $max_bytes bytes" >&2; exit 1; }
    # Bound the write here: the unprivileged caller cannot signal this process. Not exec'd, so
    # the EXIT trap still cleans up "$dir".
    /usr/bin/timeout -k 3 15 /usr/bin/rtl8370-ctl apply "$tmp"
    ;;
  get)
    if [ $# -eq 3 ] && [ "$2" = "port" ] && [ "$3" = "all" ]; then
      exec /usr/bin/timeout -k 3 15 /usr/bin/rtl8370-ctl get port all
    elif [ $# -eq 2 ] && [ "$2" = "arl" ]; then
      exec /usr/bin/timeout -k 3 15 /usr/bin/rtl8370-ctl get arl
    else
      usage
    fi
    ;;
  *)
    usage
    ;;
esac
