#!/usr/bin/env bash
set -euo pipefail

CONFIG="${BRIGHTNESS_AUTOMATION_CONFIG:-$HOME/.config/brightness-automation/env}"
if [[ -f "$CONFIG" ]]; then
  # shellcheck disable=SC1090
  source "$CONFIG"
fi

BACKLIGHT_DEVICE="${BRIGHTNESS_BACKLIGHT_DEVICE:-intel_backlight}"
BACKLIGHT_PATH="${BRIGHTNESS_SYNC_BACKLIGHT:-/sys/class/backlight/${BACKLIGHT_DEVICE}}"
STEP="${BRIGHTNESS_STEP:-10}"
DEBOUNCE_MS="${BRIGHTNESS_APPLY_DEBOUNCE_MS:-180}"
STATE_DIR="${XDG_RUNTIME_DIR:-/tmp}/brightness-automation"
STATE_FILE="$STATE_DIR/target-percent"
STAMP_FILE="$STATE_DIR/target-stamp"
LOCK_FILE="$STATE_DIR/lock"

mkdir -p "$STATE_DIR"

read_current_percent() {
  local current max
  current="$(<"${BACKLIGHT_PATH}/brightness")"
  max="$(<"${BACKLIGHT_PATH}/max_brightness")"
  printf '%s\n' "$(( (current * 100 + max / 2) / max ))"
}

clamp_percent() {
  local value="$1"
  if (( value < 1 )); then
    value=1
  elif (( value > 100 )); then
    value=100
  fi
  printf '%s\n' "$value"
}

now_ms() {
  date +%s%3N
}

apply_after_quiet_period() {
  while true; do
    sleep "$(awk "BEGIN { printf \"%.3f\", ${DEBOUNCE_MS} / 1000 }")"

    local now stamp age target
    now="$(now_ms)"
    stamp="$(<"$STAMP_FILE")"
    age="$(( now - stamp ))"

    if (( age >= DEBOUNCE_MS )); then
      target="$(<"$STATE_FILE")"
      brightnessctl -q -d "$BACKLIGHT_DEVICE" set "${target}%"
      exit 0
    fi
  done
}

if [[ "${1:-}" == "--apply-worker" ]]; then
  apply_after_quiet_period
fi

if [[ "$#" -ne 1 || ! "$1" =~ ^(up|down)$ ]]; then
  echo "Usage: $(basename "$0") up|down" >&2
  exit 2
fi

(
  flock 9

  current="$(read_current_percent)"
  if [[ -f "$STATE_FILE" ]]; then
    base="$(<"$STATE_FILE")"
  else
    base="$current"
  fi

  case "$1" in
    up) target="$(( base + STEP ))" ;;
    down) target="$(( base - STEP ))" ;;
  esac

  target="$(clamp_percent "$target")"
  printf '%s\n' "$target" >"$STATE_FILE"
  now_ms >"$STAMP_FILE"

  "$HOME/.local/bin/brightness-osd" "$target" || true
) 9>"$LOCK_FILE"

if ! pgrep -f "$HOME/.local/bin/brightness-step --apply-worker" >/dev/null 2>&1; then
  nohup "$HOME/.local/bin/brightness-step" --apply-worker >/dev/null 2>&1 &
fi
