#! /bin/sh
### vim:ft=sh
### Frank Terbeck <ft@bewatermyfriend.org>
### Last-Modified: Wed Sep 12 16:16:26 2007

### binary path
FDM="fdm"

### normally, this var is empty, unless I'm chasing bugs.
FDM_OPTIONS=""

### where should I put logfiles?
LOGFILE="${HOME}/var/log/fdm_fetch.log"

### expression to look for in the logs
#EXPR='(error\. abort|child not running)'
EXPR=''

### move log, if expression matched? (test: 'yes')
MOVE_LOG='nah, thanks.'

### remove the old log automatically? (test: 'yes')
RM_OLDLOG='nope'

### when saving a log, because it matched $EXPR, how to tag it?
SAVESTR='saved'

### mail user on certain events? (test: 'no')
MAIL_ME='hell yes'

### what user?
NAME='hawk'

export PATH="${PATH}:/usr/local/sbin:/usr/local/bin"

mail_user() {
  [ "${MAIL_ME}" = "no" ] || [ -z "${NAME}" ] && return 0
  if [ "${MOVE_LOG}" = "yes" ] ; then
    __end="The logfile was moved to '${2}'."
  else
    __end="The logfile was not moved."
  fi
  mail -s "getmail.sh: ${1}" ${NAME} > /dev/null 2>&1 << __EOF__
Hello, I am your mail retrieval script.
I found the expression you were telling me to look for.

  binary:     '${FDM}'
  expression: '${EXPR}'
  logfile:    '${LOGFILE}'

${__end}
__EOF__
  return 0
}

check_log() {
  i=0
  [ -z "${EXPR}" ] && return 1
  if grep -qE "${EXPR}" "${LOGFILE}" ; then
    while [ -e "${LOGFILE}_${SAVESTR}.${i}" ] ; do i=$(($i + 1)) ; done
    if [ "${MOVE_LOG}" = "yes" ] ; then
      mv "${LOGFILE}" "${LOGFILE}_${SAVESTR}.${i}"
    fi
    mail_user "fdm: expression (${EXPR}) found." "${LOGFILE}_${SAVESTR}.${i}"
  fi
  return 0
}

remove_log() {
  [ "${RM_OLDLOG}" = "yes" ] && rm -f "${LOGFILE}"
}

__ret=0
case "${1}" in
  (log*)
    printf -- '--- fdm fetch '    >>    "${LOGFILE}"

    if [ -n "${2}" ] ; then
      printf -- '(%s) ' "${2}"    >>    "${LOGFILE}"
    fi

    date +'%Y-%m-%d~%H:%M:%S'     >>    "${LOGFILE}"
    "${FDM}" ${FDM_OPTIONS} fetch >>    "${LOGFILE}" 2>&1
    __ret=$?
    check_log
    remove_log
    ;;

  (*)
    "${FDM}" ${FDM_OPTIONS} fetch
    __ret=$?
    ;;
esac

exit ${__ret}