#!/bin/bash
# moc_alarm.sh: executes a default command as an alarm.
# author: bumblehead
#
# moc_alarm will execute a command stored in $alarm_act
# when system time matches a given time of '$hour:$minute' (example, 8:30)
# a time may be assigned to the alarm as an argument to the script.
#
# example: execute moc_alarm and use default time,
#
# bash ./moc_alarm.sh         -> (alarm time is default)
# bash ./moc_alarm.sh 16:00   -> (alarm time is 16:00)
# bash ./moc_alarm.sh 8:45    -> (alarm time is 08:45)
# bash ./moc_alarm.sh 25      -> (alarm time is default)
# bash ./moc_alarm.sh 11      -> (alarm time is 11:00)
# bash ./moc_alarm.sh 12:800  -> (alarm time is 12:00)

# change the value of these variables for your own preference

default_hour=8     # default hour
default_minute=0   # default minute

# command to execute when system time matches alarm time
alarm_act="mocp --clear --append /home/chris/Music/wfmu32.pls --play"


#--Begin-Script-------------------------------------------------------

# check to see if string is numeric
function isNumeric(){ 
    # grep:
    # -q: grep will not print output
    # -v: invert, select non-matching lines
    if [[ -z $@ ]]; then
      echo "nil" | grep -q -v "[^0-9]";
    else
      echo "$@"  | grep -q -v "[^0-9]";
    fi
}

# '$1': first argument (if any) called w/ script 
if [ -n "$1" ]; then
    arg1=$1; # use $1 if exists, else use default
else 
    arg1="$default_hour:$default_minute"; 
fi

#token delimeter ':'
#place tokens in ${time_array[]}
IFS=":"
declare -a time_array=($arg1)
unset IFS

# if 'hour' is numeric and less than 24, valid_hour == 1
valid_hour=0  #'10#' specifies a base 10
if isNumeric ${time_array[0]}; then
    if [[ 10#${time_array[0]} -le 24 ]]; then
        valid_hour=1;
    fi
fi

if [[ valid_hour -eq 1 ]]; then
    AlarmH=${time_array[0]};
else
    AlarmH=$default_hour;
fi

# if 'minute' is numeric and less than 60, valid_minute == 1
valid_minute=0 
if isNumeric ${time_array[1]}; then
    if [[ 10#${time_array[1]} -le 60 ]]; then
        valid_minute=1;
    fi
fi

if [[ $valid_minute -eq 1 ]]; then
    AlarmM=${time_array[1]};
else
    AlarmM=$default_minute;
fi

echo "Alarm set: $(printf %02d $AlarmH):$(printf %02d $AlarmM)"

# check system time twice every minute
# if system time == alarm time, activate alarm and break loop
loop_times=0
trigger=0
while [[ $trigger == 0 ]]
do
  sleep 30
  cur_date_dy=`eval date +%a` #ex: FRI
  cur_date_hr=`eval date +%H` #24format
  cur_date_mn=`eval date +%M` #minute
  
  if [[ 10#$cur_date_hr -eq 10#$AlarmH ]]; then
      if [[ 10#$cur_date_mn -eq 10#$AlarmM ]]; then
          trigger=1;
          echo "ACTIVATED: $cur_date_hr:$cur_date_mn ($cur_date_dy)";
          $alarm_act;
      fi
  fi
done



