#!/bin/bash -p
# © 2009-2013 Gert-jan Los <los@hacke.rs>
# License: GPL v3 or later (http://www.gnu.org/licenses/gpl-3.0.txt)

usage() {
	cat <<-EOT
	usage: ${0##*/} [-h] [-V] [-q QUEUE] [-mldbv] -f FILE {-t TIMESPEC|TIMESPEC}
	       ${0##*/} [-h] [-V] [-q QUEUE] [-mldbv] {-t TIMESPEC|TIMESPEC} [COMMAND...]
	       ${0##*/} [-h] -c JOB...
	    -h: show this hеlp
	    -V: print version number and exit
	    -c: cat listed JOBs to stdout
	    -l: an alias for atq
	    -d: an alias for atrm
	    -q: use specified QUEUE (default: a)
	    -m: send mail on completion even if there was no output
	    -f: read the job from FILE, instead of stdin or the command lines
	    -t: run at TIMESPEC given as [[CC]YY]MMDDhhmm[.ss] or hh:mm
	    -v: show the time the job will be executed 
	EOT
	exit 1
}


# -- options --

options=()
file=false
timespec=''
while getopts "hcVq:f:mldbvt:" opt "$@" ;do
	case "$opt" in
	h) usage ;;
	V|c|l|d) exec /usr/bin/at "$@" ;;
	q) options+=('-q' "$OPTARG") ;;
	m) options+=('-m') ;;
	f) file=true ; options+=('-f' "$OPTARG") ;;
	t) timespec="$OPTARG" ;;
	v) options+=('-v') ;;
	--) break ;;
	*) usage ;;
	esac
done
shift $((OPTIND-1))
if [ -z "$timespec" ] ;then
	[ $# -gt 0 ] || usage
	timespec="$1"
	shift
fi
if $file ;then
	[ $# -eq 0 ] || usage
fi

# --- main ---
#echo at "$timespec" "${options[@]}" "[${*// /\\ }]" ; exit
if [ $# -gt 0 ] ;then
	q="'"
	bs='\'
	for x in "${@//$q/$q$bs$q$q}" ;do echo -n "'$x' " ; done |
	{ /usr/bin/at "$timespec" "${options[@]}" 2>&1 || exit $? ; } |
	grep -v \
		-e '^warning: commands will be executed using /bin/sh$' \
		-e '^job [0-9]\+ at ' \
		1>&2
	exit 0
else
	exec /usr/bin/at "$timespec" "${options[@]}"
fi

