#!/bin/sh
#
# Usage:
#   notify "message"
#   notify -t "title" "message"
#
# Sends a desktop notification.
# Uses OSC escape sequences when a terminal is attached,
# falls back to osascript on macOS.

title=""
if [ "$1" = "-t" ] || [ "$1" = "--title" ]; then
  shift
  title=$1
  shift
fi

if [ $# -eq 0 ]; then
  echo "usage: notify [-t title] message" >&2
  exit 1
fi

body="$*"

# shellcheck disable=SC2312
if [ -t 1 ]; then
  # terminal attached — use OSC escape sequences
  if [ -n "${TMUX}" ]; then
    if [ -n "${title}" ]; then
      printf "\033Ptmux;\033\033]777;notify;%s;%s\007\033\\" "${title}" "${body}"
    else
      printf "\033Ptmux;\033\033]9;%s\007\033\\" "${body}"
    fi
  else
    if [ -n "${title}" ]; then
      printf '\033]777;notify;%s;%s\007' "${title}" "${body}"
    else
      printf '\033]9;%s\007' "${body}"
    fi
  fi
elif [ "$(uname)" = "Darwin" ]; then
  # no terminal — use osascript on macOS
  # shellcheck disable=SC2250
  osascript -e "display notification \"$body\" with title \"${title:-Notification}\""
fi
