#!/bin/bash
# KO/Pi alarm script for pdaXrom
# Made by Attila Darazs <zumi@pdaxrom.org>

suspend() {
  # if KO/Pi is not running, exit. We don't want to wake up for nothing
  if [ `ps x|grep -c "[/ \t]kopi[^-]"` == 0 ]; then
    exit 0
  fi
  mkdir -p /var/spool/at

  NOW=`date +%s`

  # next normal alarm time
  if [ -e ~/.kopi_next_alarm ]; then
    NEXT=`cat ~/.kopi_next_alarm |head -n 1`
    NEXT=`date -d "$NEXT" +%s`
    NEXT=$(( $NEXT - 10 ))
  else
    NEXT=-1
  fi

  # next suspended alarm time
  if [ -e ~/.kopi_suspend_alarm ]; then
    SUSPEND=`cat ~/.kopi_suspend_alarm |head -n 1`
    SUSPEND=`date -d "$SUSPEND" +%s`
    SUSPEND=$(( $SUSPEND - 10 ))
  else
    SUSPEND=-1
  fi

  # decide which one to use
  if ([ $NEXT -lt $SUSPEND ] || [ $(( $SUSPEND - $NOW )) -lt 0 ]) && [ $(( $NEXT - $NOW )) -gt 0 ]; then
    AT=/var/spool/at/$NEXT.00000$$
#    AT=/var/spool/at/$NEXT.$$
  elif [ $SUSPEND -lt $NEXT ] && [ $(( $SUSPEND - $NOW )) -gt 0 ]; then
    AT=/var/spool/at/$SUSPEND.00000$$
#    AT=/var/spool/at/$SUSPEND.$$
  else
    exit 0
  fi

  echo '#!/bin/bash' >$AT.new
  echo 'rm -f $0' >>$AT.new
  chmod 755 $AT.new
  mv $AT.new $AT
  echo >/var/spool/at/trigger
  return 0
}

resume() {
  rm -f /var/spool/at/*.00000*
  return 0
}

case "$1" in
  suspend)
  	suspend
	;;
  resume)
  	resume
	;;
  *)
	echo "Usage: $0 {suspend|resume}"
	exit 1
esac

exit $?

