#!/usr/bin/env bash
# timer-run <total_seconds> [label]
# Runs entirely in background. No terminal needed after launch.
# Sends a dunst notification + audio beep when done.
#
# Install: ~/.config/scripts/timer-run  (companion: timer-pick in same dir)

TOTAL="${1:?missing seconds}"
LABEL="${2:-}"

# ── ensure runtime dir env vars are set for audio/dbus in detached context ────
if [[ -z "${XDG_RUNTIME_DIR:-}" ]]; then
  export XDG_RUNTIME_DIR="/run/user/$(id -u)"
fi
# paplay resolves the PulseAudio/PipeWire socket via PULSE_RUNTIME_PATH
if [[ -z "${PULSE_RUNTIME_PATH:-}" ]]; then
  export PULSE_RUNTIME_PATH="${XDG_RUNTIME_DIR}/pulse"
fi

# ── detach from terminal immediately ──────────────────────────────────────────
# Preserve the full environment across the setsid re-exec (no login shell).
if [[ -t 0 || -t 1 || -t 2 ]]; then
  ( trap '' SIGHUP; exec setsid bash "$0" "$TOTAL" "$LABEL" </dev/null >/dev/null 2>&1 ) &
  exit 0
fi

# ── sleep until done ──────────────────────────────────────────────────────────
sleep "$TOTAL"

# ── format a human-readable duration ─────────────────────────────────────────
fmt_dur() {
  local s=$1 h=0 m=0 out=""
  h=$(( s / 3600 )); s=$(( s % 3600 ))
  m=$(( s / 60  )); s=$(( s % 60  ))
  (( h > 0 )) && out+="${h}h "
  (( m > 0 )) && out+="${m}m "
  (( s > 0 || (h == 0 && m == 0) )) && out+="${s}s"
  echo "${out% }"
}

DURATION_STR=$(fmt_dur "$TOTAL")
NOTIF_SUMMARY="⏰ Timer done${LABEL:+ — $LABEL}"
NOTIF_BODY="Set for ${DURATION_STR}. Finished at $(date '+%H:%M:%S')."

# ── dunst notification ────────────────────────────────────────────────────────
# notify-send needs DBUS_SESSION_BUS_ADDRESS. If not in env, find it via the
# running dunst process (reliable on single-user Wayland/Hyprland setups).
if [[ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ]]; then
  local_uid=$(id -u)
  # try to grab it from the environment of any process owned by this user
  for pid in $(pgrep -u "$local_uid" dunst 2>/dev/null); do
    addr=$(cat /proc/$pid/environ 2>/dev/null \
           | tr '\0' '\n' \
           | grep '^DBUS_SESSION_BUS_ADDRESS=' \
           | cut -d= -f2-)
    if [[ -n $addr ]]; then
      export DBUS_SESSION_BUS_ADDRESS="$addr"
      break
    fi
  done
fi

if command -v notify-send &>/dev/null; then
  notify-send \
    --urgency=critical \
    --expire-time=0 \
    --icon=alarm-timer \
    "$NOTIF_SUMMARY" \
    "$NOTIF_BODY"
fi

# ── audio alert ───────────────────────────────────────────────────────────────
_ALARM_SOUND="/usr/share/sounds/freedesktop/stereo/alarm-clock-elapsed.oga"

if command -v paplay &>/dev/null && [[ -f "$_ALARM_SOUND" ]]; then
  paplay "$_ALARM_SOUND" 2>/dev/null
elif command -v canberra-gtk-play &>/dev/null; then
  canberra-gtk-play --id=alarm-clock-elapsed 2>/dev/null
fi
