#!/usr/bin/env bash
# Background timer: sleeps, notifies, rings thrice in 30s unless dismissed
# Usage: timer-notify.sh <seconds> <label> [--verbose]

DURATION=${1:?missing duration}
LABEL=${2:-"00:00:00"}
VERBOSE=0
[[ "${3:-}" == "--verbose" ]] && VERBOSE=1

if [[ $VERBOSE -eq 1 ]]; then
  printf 'Timer started: %s\n\n' "$LABEL"
  for (( i=DURATION; i>0; i-- )); do
    printf '\r  %02d:%02d:%02d remaining...' $((i/3600)) $(( (i%3600)/60 )) $((i%60))
    sleep 1
  done
  printf '\r  00:00:00 — timer fired!      \n\n'
else
  sleep "$DURATION"
fi

# Find a ring sound (freedesktop stereo sounds)
SOUND=""
for candidate in \
    /usr/share/sounds/freedesktop/stereo/complete.oga \
    /usr/share/sounds/freedesktop/stereo/alarm-clock-elapsed.oga \
    /usr/share/sounds/freedesktop/stereo/bell.oga \
    /usr/share/sounds/freedesktop/stereo/phone-incoming-call.oga; do
  [[ -f "$candidate" ]] && { SOUND="$candidate"; break; }
done

play_sound() {
  [[ -z "$SOUND" ]] && return
  if command -v paplay &>/dev/null; then
    paplay "$SOUND" &
  elif command -v pw-play &>/dev/null; then
    pw-play "$SOUND" &
  fi
}

# Send notification — blocks (-w) until dismissed or timeout
# Rings play while this is waiting; kill -0 checks if it's still alive
if command -v dunstify &>/dev/null; then
  dunstify -w -u critical -i alarm-clock \
    -A "default,Dismiss" \
    -t 30000 \
    "⏱ Timer: $LABEL" "Your timer has expired." &
else
  notify-send -w -u critical -i alarm-clock \
    -t 30000 \
    "⏱ Timer: $LABEL" "Your timer has expired." &
fi
NOTIF_PID=$!

play_sound                                              # ring 1 — immediately
sleep 10; kill -0 "$NOTIF_PID" 2>/dev/null && play_sound  # ring 2 — 10s
sleep 10; kill -0 "$NOTIF_PID" 2>/dev/null && play_sound  # ring 3 — 20s

wait "$NOTIF_PID" 2>/dev/null || true
