#!/usr/bin/env bash
# notifysend -- wrapper around notify-send that automatically replaces the
#               previous notification from the same program

. lib.bash || exit

usage() {
	echo "Usage: $progname [options] <title> <body>"
	echo
	echo_opt "-u LEVEL"	"urgency (low, normal, critical)"
	echo_opt "-t TIME"	"expiry timeout (milliseconds)"
	echo_opt "-a NAME"	"application name for the icon"
	echo_opt "-i ICON"	"icon name"
	echo_opt "-e"		"transient notification"
	echo_opt "-h HINT"	"custom hint (type:name:value)"
	echo_opt "-r NAME"	"state name to replace last notification"
}

opt_urgency=
opt_expire=
opt_appname=
opt_icon=
opt_category=
opt_transient=0
opt_hints=()
opt_printid=0
opt_replaceid=

while getopts ":a:c:eh:i:pr:t:u:" OPT; do
	# Handle most notify-send options except --action and --wait
	# (both of which conflict with the stdout usage of --print-id).
	case $OPT in
	u) opt_urgency=$OPTARG;;
	t) opt_expire=$OPTARG;;
	a) opt_appname=$OPTARG;;
	i) opt_icon=$OPTARG;;
	c) opt_category=$OPTARG;;
	e) opt_transient=1;;
	h) opt_hints+=("$OPTARG");;
	p) opt_printid=1;;
	r) opt_replaceid=$OPTARG;;
	*) lib:die_getopts;;
	esac
done; shift $((OPTIND-1))

if (( $# > 2 )); then
	vdie "excess arguments"
fi

args=()
if [[ $opt_urgency ]]; then
	args+=(-u "$opt_urgency")
fi
if [[ $opt_expire ]]; then
	args+=(-t "$opt_expire")
fi
if [[ $opt_appname ]]; then
	args+=(-a "$opt_appname")
fi
if [[ $opt_icon ]]; then
	args+=(-i "$opt_icon")
fi
if [[ $opt_category ]]; then
	args+=(-c "$opt_category")
fi
if (( opt_transient )); then
	args+=(-e)
fi
for hint in "${opt_hints[@]}"; do
	args+=(-h "$hint")
done
if [[ $opt_replaceid ]]; then
	statefile=${XDG_RUNTIME_DIR?}/notify-send.$opt_replaceid
	: >> "$statefile"
	replaceid=$(< "$statefile")
	args+=(-r "${replaceid:-0}")
fi

# Use -p optionally, as it's not yet available on Debian 11.
if (( opt_printid || opt_replaceid )); then
	replaceid=$(notify-send -p "${args[@]}" -- "$@") || exit
	if [[ $opt_replaceid ]]; then
		echo "$replaceid" > "$statefile"
	fi
	if (( opt_printid )); then
		echo "$replaceid"
	fi
else
	notify-send "${args[@]}" -- "$@"
fi
