#!/bin/sh
#
# dependencies: fyi

init_variables() {
  summary=
  body=
  category=
  identifier=
  expire_time=0
  replace_id=0
}

# shellcheck disable=SC2249
parse_command_line() {
  while getopts c:i:s:t: opt; do
    case "${opt}" in
      c) category="${OPTARG}" ;;
      i) identifier="${OPTARG}" ;;
      t) expire_time="${OPTARG}" ;;
      ?) exit_error ;;
    esac
  done
  shift "$((OPTIND - 1))"

  summary="$1"
  body="$2"
}

validate_command_line() {
  if [ -z "${summary}" ]; then
    exit_error 'missing summary argument'
  fi
  if ! echo "${expire_time}" | grep -q -E '^[0-9]*$'; then
    exit_error 'expire time must be a number'
  fi
}

exit_error() {
  [ -z "$1" ] || printf '%s\n' "$(basename "$0"): $1"
  exit 1
} >&2

send_notification() {
  if [ -n "${identifier}" ]; then
    NOTIFICATION_FILE="${XDG_RUNTIME_DIR:-/tmp}/notification_${identifier}"
    if [ -f "${NOTIFICATION_FILE}" ]; then
      replace_id=$(cat "${NOTIFICATION_FILE}")
    fi
  fi

  NOTIFICATION_ID=$(
    fyi --print-id \
      --replaces "${replace_id}" \
      --category "${category}" \
      --expire-time "$((expire_time * 1000))" \
      "${summary}" \
      "${body}"
  )

  if [ -n "${identifier}" ]; then
    echo "${NOTIFICATION_ID}" >"${NOTIFICATION_FILE}"
  fi
}

init_variables
parse_command_line "$@"
validate_command_line

send_notification
