#!/bin/sh

# 10 April 2006
# at scheduler script
#
# This script is based on the standard pdaXrom at distribution.
# It adds support for -c and -d flags, and ignores -q flags.
# It uses job ids reported on stdout in normal at format.
# As with the original script, error checking and reporting
# is minimal, so please use it carefully.

FN=""
WHEN=""
while [ $# -gt 0 ]; do
  LASTARG=$1
  if [ "-f" = "$LASTARG" ]; then
    # Name of file containing command(s) to execute
    shift
    FN=$1
  elif [ "-c" = "$LASTARG" ]; then
    # cat the specified job to stdout
    shift
    JOBID=$1
    JFLAG="c"
  elif [ "-d" = "$LASTARG" ]; then
    # Delete the specified job
    shift
    JOBID=$1
    JFLAG="d"
  elif [ "-q" = "$LASTARG" ]; then
    # Ignore this flag; no use to us (queues/priorities)
    shift
  else
    # The remainder of the parameters should be the date/time
    if [ -n "$(echo $LASTARG | grep '\.')" ]; then
      if [ "8" = "$(echo $LASTARG | awk '{ print length($1) }')" ]; then
        # gpe pim apps give dates in form DD.MM.YY, which is useless
        LASTARG=$(echo $LASTARG | awk '{ print substr($1,4,2)"/"substr($1,1,2)"/"substr($1,7,2) }')
      fi
      LASTARG=$(echo $LASTARG | sed -e 's/\./\//g')
    fi
    WHEN="$WHEN $LASTARG"
  fi
  shift
done

if [ -n "$FN" ]; then
  # We have a file name; add a new item for execution
  # Set job id to pid so it is likely to be unique
  JOBID=$$
  if [ -z "$LASTARG" ]; then
    echo "Error: no date specified!"
    exit 1
  else
    if WHEN=`date -d "$WHEN" +%s`; then
      AT=/var/spool/at/$WHEN.$JOBID
      echo '#!/bin/sh' >$AT.new
      /bin/cat $FN >>$AT.new
      # Cater for files with no trailing new line
      echo "" >>$AT.new
      echo 'rm -f $0' >>$AT.new
      /bin/chmod 755 $AT.new
      /bin/mv $AT.new $AT
      echo >/var/spool/at/trigger
      # The format of this output matches standard 'at', 
      #  and is relied on for job id at least
      echo "job $JOBID at "$(date -d "1/1/70 +$WHEN seconds" +"%Y-%m-%d %H:%M")
    else
      exit $?
    fi
  fi
elif [ -n $JOBID ]; then
  # We have a job id to look up
  if [ "c" = "$JFLAG" ]; then
    # cat the job to stdout
    cat /var/spool/at/*.$JOBID
    echo >/var/spool/trigger
    exit 0
  elif [ "d" = "$JFLAG" ]; then
    # delete the job
    rm /var/spool/at/*.$JOBID
    echo >/var/spool/trigger
    exit 0
  fi
else
  echo "Error: incorrect parameters given!"
  exit 1
fi
