#!/usr/bin/env sh

help() {
  [ 0 -lt $# ] && >&2 echo "$*"
  >&2 cat <<EOF
Usage: $0 [*options] command [*args]

Options:
  -h
  -t TO       default: your login-user
  -f FROM     default: your login-user
  -s SUBJECT  default: "timer: [command *args]"
  -v          pipes output through
  -e          send email only on error (command exit-code != 0)
  -o          send email only if command writes on STDOUT or STDERR (default)
  -a          send always email
EOF
  exit 1
}

eval set -- "$(getopt -n "$0" "ht:f:s:aev" "$@")"
while [ 0 -lt $# ]
do
  case "$1" in
  -h) help ;;
  -s) shift ; subject="$1" ;;
  -t) shift ; to="$1" ;;
  -f) shift ; from="$1" ;;
  -e) on=error ;;
  -o) on=output ;;
  -a) on=always ;;
  -v) verbose=true ;;
  --) shift ; break ;;
  *) help "Unknown option: $1" ;;
  esac
  shift
done

subject="${subject:-timer: $*}"
on=${on:-output}
verbose=${verbose:-false}
to="${to:-${LOGNAME:-$USER}}"
from="${from:-${LOGNAME:-$USER}}"

output="$(mktemp)"
trap "rm -f -- $output" EXIT

if $verbose
then
  2>&1 "$@" | tee $output
  r=$?
else
  >$output 2>&1 "$@"
  r=$?
fi

if [ always = $on ] || [ error = $on -a 0 -lt $r ] || [ output = $on -a -s $output ]
then
  <$output  mail -s "$subject" -r "$from" -- "$to" || exit 97
fi

exit $r