#!/bin/sh
#
# Copyright (C) 2008-2010, William Trevor King <wking@drexel.edu>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Can't drag yourself away from your software? Set an alarm!
#
# Caveats:
#  You'll have to keep your current terminal open until the alarm goes off,
#  or the message woln't be printed to the screen.
#  The sound will still play.
#
#  Echoed text may not appear if the terminal is in curses mode (e.g. Emacs)
#
#  Your message text cannot contain any shell-sensitive characters,
#  since it gets expanded at least twice before AT sees it.
#
#  Minute resolution, since that's the best `at` can do.
#
#  Script is hugely larger than the actual code,
#  but hopefully well commented inside and user friendly outside. :p

# Alarms should make some noise.
# Adapt this command to generate something on your particular system.
# Googling `beep wav` worked pretty well for me, or record your own :).
ALARM_SOUND_CMD="aplay $HOME/Music/system/towerclo.wav"
ECHO="/bin/echo -e" # echo command must expand '\n' to newline

Usage ()
{
    ERROR=$1
    $ECHO "$ERROR"
    $ECHO "
usage: alarm <some-time> [some message]

where
  <some-time> will be recognized by at (see man at).
  'some message' will be printed to the current terminal.
<some-time> must be the first argument, so if your time string is
several words long, enclose it in quotes ('6:00 tomorrow') to keep the
shell from breaking it into multiple arguments."
}

# If there is no time argument, print a usage string.
if [ $# -lt 1 ]
then
    Usage 'Incorrect number of arguments'
    return 1
fi

# Initialize AT_CMD, the command we will send AT, and read in arguments.
AT_CMD=""
TIME=$1
shift
MESSAGE="$*"

Append_cmd () # Add command.  In case you want to add whistles to the bells ;)
{
    NEW_CMD=$1
    AT_CMD="$AT_CMD\n$NEW_CMD"
}

Append_cmd "$ALARM_SOUND_CMD"

if [ -n "$MESSAGE" ] # if there is a non-zero message string...
then                 # ... append an $ECHO cmmd.
    TERMINAL_NAME=$(tty)
    Append_cmd "$ECHO \"$MESSAGE\" > $TERMINAL_NAME"
fi

if false
then # debugging printout
    $ECHO "'$AT_CMD'"
    $ECHO 
    $ECHO "at '$TIME'"
fi

# send the command off to at.
$ECHO "$AT_CMD" | at "$TIME" || Usage 'Bad time?'

# use `atq` to list outstanding jobs.
# use `at -c <job-number>` to view the script at executes for debugging.
