#!/bin/sh

POWER="${1:-}"
LOCK=/run/wfb-power.lock
STATE=/run/wfb-power

case "$POWER" in
  ''|*[!0-9]*) exit 2 ;;
esac
[ "$POWER" -ge 5 ] && [ "$POWER" -le 100 ] || exit 2

# The runtime state is tmpfs. Do not rewrite /etc/wfb.yaml while a knob moves.
printf '%s\n' "$POWER" >"$STATE"

if ! mkdir "$LOCK" 2>/dev/null; then
  exit 0
fi
trap 'rmdir "$LOCK" 2>/dev/null || true' EXIT HUP INT TERM

if pidof wfb_tx wfb_rx wfb_tun wifilink >/dev/null; then
  # RTL8812EU expects the OpenIPC scalar multiplied by 50 mBm.
  iw wlan0 set txpower fixed $((POWER * 50))
  logger -t wfb-power "runtime txpower=$POWER"
  exit 0
fi

logger -t wfb-power "txpower=$POWER -> WFB preflight"
/usr/bin/link-mode preflight
