#!/usr/bin/env bash
# Test buzzer so screen-brightness daemon raises backlight (ALERT) and holds
# during COOLDOWN. Holds buzzer ON for 3+ seconds so the daemon's 2s poll sees it.
#
# reTerminal DM: /sys/class/leds/usr-buzzer/brightness (0 = off, 1 = on)
# Run as root: sudo ./test-buzzer-brightness.sh

set -e
BUZZER="/sys/class/leds/usr-buzzer/brightness"
MAX="/sys/class/leds/usr-buzzer/max_brightness"

if [[ ! -f "$BUZZER" ]]; then
  echo "ERROR: Buzzer not found at $BUZZER" >&2
  exit 1
fi

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Run as root: sudo $0" >&2
  exit 1
fi

# Quick check: is the daemon running? (so we know what to expect)
echo "--- Pre-check ---"
if systemctl is-active --quiet screen-brightness.service 2>/dev/null; then
  echo "  screen-brightness.service: active"
  if [[ -f /run/screen-brightness/state ]]; then
    echo "  Current state:"
    sed 's/^/    /' /run/screen-brightness/state
  else
    echo "  (no /run/screen-brightness/state yet)"
  fi
  echo "  Recent logs:"
  journalctl -u screen-brightness.service -n 3 --no-pager 2>/dev/null | sed 's/^/    /' || true
else
  echo "  screen-brightness.service: NOT ACTIVE — start it with: sudo systemctl start screen-brightness.service"
  echo "  Brightness will not change until the daemon is running."
fi
echo ""

# Hold buzzer ON for 3 seconds so the daemon's 2s poll interval will see it
ON_VAL=255
if [[ -f "$MAX" ]]; then
  ON_VAL="$(cat "$MAX" 2>/dev/null || echo 255)"
fi

echo "Beeping: 3 short beeps, then buzzer ON for 3 s (watch brightness go to 5)..."
for i in 1 2 3; do
  echo "$ON_VAL" > "$BUZZER"
  sleep 0.15
  echo 0 > "$BUZZER"
  sleep 0.25
done
echo "$ON_VAL" > "$BUZZER"
sleep 3
echo 0 > "$BUZZER"

echo "Buzzer off. Brightness should stay at 5 for ~10 s (cooldown), then return to ambient."
echo ""
echo "--- After (check state and logs) ---"
if [[ -f /run/screen-brightness/state ]]; then
  echo "  State:"
  sed 's/^/    /' /run/screen-brightness/state
fi
echo "  Recent logs:"
journalctl -u screen-brightness.service -n 8 --no-pager 2>/dev/null | sed 's/^/    /' || echo "    (no logs or service not running)"
