#! /bin/bash -

# H.A.Trujillo
# Last Change:     27 Apr 2021

# Kitchen timer, of sorts:  beeps after (or at a) specified time.
#
# usage:  timer n	
#	  timer -c n	count to 20 blips
#	  timer -a n	alert noise and screen message
#
#	n = either:
#		- time to wait,
#		     in seconds	    	eg, timer 300
#		     in hms format	    timer 10m30s
#
#		- time at which to ring	    timer 16:00	     (24-hour clock)
			
#-------
# !! Lines 54-57 assume "at" is enabled with < 10-min granularity.
# !!  Comment out if "at" is not running
#-------

SOUND=/System/Library/Sounds/Tink.aiff
PLAYER=/usr/bin/afplay

case "$1" in
    -c) 
	show_count=1
	shift
	;;
    -a)
	showalert=1
	SOUND=$HOME/Library/Sounds/Bell.wav
	shift
	;;
    -h) 
	sed -n '6,17{s/#/ /; p;}' < $0
	exit
	;;
esac

arg=$*

# convert input to seconds
if [[ $arg =~ : ]] ; then	# Is $* an absolute time?	(hh:mm)
    now=$(date +%s)
    start=$(date -j -f "%R" $arg +%s)
    if [ $now -gt $start ] ; then 	#   tomorrow?
	start=$(( start + 86400 )) 
    fi
    arg=$(( start - now ))

    if [ $arg -gt 1000 ] ; then		#   if >15 min to go, resubmit when closer
	resubmit_at=$(( $arg - 500 ))
	echo $0 $* | at + $(( $resubmit_at / 60 )) minutes 2> /dev/null
	exit
    fi
else
    if [[ $arg =~ h ]] ; then	# Is $* in *h*m*s format?
	time=$(( 3600 * ${arg%h*} ))
	arg=${arg#*h}
    fi
    if [[ $arg =~ m ]] ; then
	time=$(( $time + 60 * ${arg%m*} ))
	arg=${arg#*m}
    fi
    if [[ $arg =~ s ]] ; then
	arg=${arg%s*}
    fi
fi
time=$(( $time + ${arg:-0} ))


#  Make some noise at the appointed hour
sleep ${time:-0}

if [ "$showalert" ] ; then
#    msg=`cat /tmp/time`
#    growlnotify -m "${msg=Calendar Alert}"
    growlnotify -m "Calendar Alert"
    $PLAYER $SOUND
    exit
fi

if [ "$show_count" == "1" ] 
  then
    x=20
    until [ $x == 0 ] ; do
	let x--
	printf "%-3s" "$x "; $PLAYER $SOUND 
	sleep 1
    done
    echo ""
  else
    $PLAYER $SOUND 
    $PLAYER $SOUND 
    $PLAYER $SOUND 
fi

exit

____________________________

# v0:	   		a csh alias
# v1	 		a short script, all in seconds
# v2      15mar21	hms time format also acceptable
# v2.0.1  17mar21	absolute-time input
# v2.1    16apr21	calendar alerts
