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

MODE=""
VOLUME="90"
# Default bell sample: a short single strike (2s) for repeated chimes
BELL="/home/kuhnn/.openclaw/workspace/assets/sfx/church_bell_2s.wav"
PAUSE_SEC="1.0"

usage() {
  cat <<EOF
Usage: $(basename "$0") --mode hour|half [--volume 0-100] [--bell <path>] [--pause <sec>]
- hour: strikes N times based on local hour (1-12)
- half: strikes once
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --mode) MODE="$2"; shift 2;;
    --volume) VOLUME="$2"; shift 2;;
    --bell) BELL="$2"; shift 2;;
    --pause) PAUSE_SEC="$2"; shift 2;;
    -h|--help) usage; exit 0;;
    *) echo "Unknown arg: $1" >&2; usage; exit 2;;
  esac
done

if [[ "$MODE" != "hour" && "$MODE" != "half" ]]; then
  echo "--mode must be hour or half" >&2
  exit 2
fi

# Set system volume best-effort
if command -v pactl >/dev/null 2>&1; then
  pactl set-sink-mute @DEFAULT_SINK@ 0 || true
  pactl set-sink-volume @DEFAULT_SINK@ "${VOLUME}%" || true
fi

if [[ ! -f "$BELL" ]]; then
  echo "Bell file not found: $BELL" >&2
  exit 1
fi

count=1
if [[ "$MODE" == "hour" ]]; then
  h=$(date +%I)  # 01-12
  h=${h#0}
  [[ -z "$h" ]] && h=12
  count=$h
fi

for ((i=1; i<=count; i++)); do
  if command -v paplay >/dev/null 2>&1; then
    paplay "$BELL" || true
  elif command -v aplay >/dev/null 2>&1; then
    aplay -q "$BELL" || true
  fi
  if (( i < count )); then
    sleep "$PAUSE_SEC"
  fi
done
