#!/bin/bash

set -o errexit
set -o nounset
set -o pipefail

function show_help ()
{
   cat >&2 <<EOF
usage: $(basename $0) [OPTION...] {MINUTES|TIME} [MESSAGE]

Place an item in the at(1) queue to display a zenity dialog.  MINUTES
must be at least 1.  TIME must have a colon, e.g. '16:22'.  The dialog
will display MESSAGE, if given, or a fortune.

MESSAGE must be only from trusted input!

OPTIONS
  -v   Verbose.
  -h   This help.

Examples
   \$ $(basename $0) -v 2
   \$ $(basename $0) 15 "Check rice"
   \$ $(basename $0) 16:22
EOF
   exit 1
}
#------------------------------------------------------------------------------

declare -i VERBOSITY=0
while getopts ":hv" opt
do
   case $opt in
       v ) ((++VERBOSITY)) ;;
       * ) show_help ;;
   esac
done
shift $(($OPTIND - 1))
#------------------------------------------------------------------------------

function squawk ()
{
    local -i NVOL=$1; shift
    if ((NVOL <= VERBOSITY)); then
        echo "$(basename $0) $(date +'%T %Z') $@"
    fi
}
#------------------------------------------------------------------------------

squawk 1 "$(date --iso) started."

declare -r when=${1:-"0"}
declare at_timespec=""

if [[ $when =~ : ]]; then
    squawk 1 "treating as time of day: '$when'"
    at_timespec="$when"
else
    squawk 1 "treating as minutes from now: '$when'"
    declare -i minutes="$when"
    ((minutes >= 1)) || show_help
    at_timespec="now + $minutes minutes"
fi
squawk 1 "at timespec: $at_timespec"

# This mess is to try to exclude from $message any occurrence of the
# character `"'.  If present, it tends to make the zenity command invalid;
# instead of showing a zenity popup, 'at' will email something like:
# sh: 44: Syntax error: Unterminated quoted string
#
declare message="$(tr '"' "'" <<<"${2:-$(fortune)}")"

if ((0 < VERBOSITY)); then
   at $at_timespec
else
   at $at_timespec 2>/dev/null
fi <<EOF
zenity --display="$DISPLAY" --info --no-wrap \
   --title="Time's Up" --text="$message" \
   &>/dev/null
EOF

squawk 1 "done."

exit 0
