#!/bin/sh
set -eu

usage() {
	cat <<-'EOF'
		Usage:
		  msg [-0|-1] [-X|-s|-S|-m|-D|-b] [MESSAGE]
		  msg -h
	EOF
}

help() {
	cat <<-'EOF'


		Options:
		  -X            send MESSAGE using the xmpp(1) command
		  -s            play(1) $XDG_DATA_HOME/msg/{good,bad}.ogg sound
		  -S            say MESSAGE using speak(1)
		  -m            send email(1) with MESSAGE as subject and empty body
		  -D            send desktop MESSAGE via notify-send(1)
		  -b            print terminal bell
		  -0            an OK message
		  -1            an error message
		  -h, --help    show this message

		  MESSAGE       the text to be sent by the relevant channel


		Send MESSAGE via all the selected channels.


		Examples:

		  Ring a terminal bell and play a sound, representing an error:

		    $ msg -1sb


		  Send an email and an XMPP message:

		    $ msg -mX 'The message goes here'
	EOF
}

for flag in "$@"; do
	case "$flag" in
		(--)
			break
			;;
		(--help)
			usage
			help
			exit
			;;
		(*)
			;;
	esac
done

sound() {
	if [ "$OK" = true ]; then
		play "$XDG_DATA_HOME"/msg/good.ogg 2>/dev/null
	else
		play "$XDG_DATA_HOME"/msg/bad.ogg 2>/dev/null
	fi
}

OK=true
XMPP=false
SOUND=false
SPEAK=false
MAIL=false
DESKTOP=false
BELL=false
ACTION_DONE=false
while getopts '01XsSmDbh' flag; do
	case "$flag" in
		0)
			OK=true
			;;
		1)
			OK=false
			;;
		X)
			XMPP=true
			ACTION_DONE=true
			;;
		(s)
			SOUND=true
			ACTION_DONE=true
			;;
		S)
			SPEAK=true
			ACTION_DONE=true
			;;
		(m)
			MAIL=true
			ACTION_DONE=true
			;;
		D)
			DESKTOP=true
			ACTION_DONE=true
			;;
		(b)
			BELL=true
			ACTION_DONE=true
			;;
		(h)
			usage
			help
			exit
			;;
		(*)
			usage >&2
			exit 2
			;;
	esac
done
shift $((OPTIND - 1))

if [ "$ACTION_DONE" = false ]; then
	sound
	usage
	help
	exit
fi


MESSAGE="${1:-}"

if [ "$XMPP" = true ]; then
	eval "$(assert-arg -- "$MESSAGE" '-X MESSAGE')"
	xmpp -m "$MESSAGE" eu@euandre.org &
fi
if [ "$SOUND" = true ]; then
	sound &
fi
if [ "$SPEAK" = true ]; then
	eval "$(assert-arg -- "$MESSAGE" '-S MESSAGE')"
	printf '%s\n' "$MESSAGE" | speak -v pt-BR &
fi
if [ "$MAIL" = true ]; then
	eval "$(assert-arg -- "$MESSAGE" '-m MESSAGE')"
	echo " " | email -s "$MESSAGE" eu@euandre.org &
fi
if [ "$DESKTOP" = true ]; then
	eval "$(assert-arg -- "$MESSAGE" '-D MESSAGE')"
	if [ "$OK" = true ]; then
		notify-send -t 5000             "$MESSAGE" &
	else
		notify-send -t 5000 -u critical "$MESSAGE" &
	fi
fi
if [ "$BELL" = true ]; then
	printf '\a' &
fi

wait