#!/bin/bash

#                      /usr/local/bin/alert
# http://crystalfaeries.net/posix/bin/alert
# celeste:crystalfaery 2021-04-24 07:24:36+00:00
# Alert the user via audio, CLI and GUI
# Usage: alert "message to display to user"
# or supply -k option or --kill to terminate all alerts
# Example: some_command && exit || alert "some_command: $?"
let help=9
case $# in
0 )	# ummm... we rather expected an argument or option
	exec $0 --help
	exit	$?	# exec not supposed to return
	;;
* )	while [[ $# -gt 0 ]]
	do
		case "${1}" in
		-v | --version )
			head -n 4 $0 | tail -n 1
			exit
			;;
		-h | --help )
			head -n $help $0
			exit
			;;
		-k | --kill )
			for signal in hup term kill
			do
				kill -"$signal" $(ps -ef --forest | grep "/bin/bash /usr/local/bin/alert" | grep -v grep | sed 's/^[^ ]* *//;s/ .*$//' ) 2>/dev/null
				sleep 15
			done
			exit	$?
			;;
		* )
			# Pop up an alert dialogue on the GUI
			echo "DISPLAY=$DISPLAY xmessage Alert: $@ && pkill alert" | at "now"
			# UH-OH! WE KILL ALL PENDING ALERTS! BAD! BAD! WE SHOULD TRACK PID!

			# Pop up an alert notice on the CLI
			echo -n "======= Alert: $@ ======= (^C to silence)"

			# Binary Back-Off Audio Alert
			player="mplayer"
			alert="/usr/share/sounds/gnome/default/alerts/bark.ogg"
			let sleep=1
			while sleep $sleep
			do
				let sleep=$sleep+$sleep
				"$player" "$alert" > /dev/null 2>&1
				sleep 1
				echo $@ | festival --tts --pipe
			done
			;;
		esac
		exit	$?
		shift	# out with the old, in with the new
	done
	;;
esac
exit	$?

