
#!/bin/sh
# File	: proc_mail-automation.sh
# By	: MaartenDeBoer.nl, 210615, 230808
# Subject	: Script to process automation by mail
# From proc_mail-subjects.sh
PGM=`basename $0|cut -d\. -f1`
VER="0.1"
TMP="/tmp/${PGM}.$$"
LOG="${HOME}/log/${PGM}.log"
HOSTNAME=`hostname|cut -d\. -f1`

DATA_DIR="${HOME}/data"
SUBJECTS_DIR="${DATA_DIR}/subjects"
DONE_DIR="${DATA_DIR}/done"
SKIP_DIR="${DATA_DIR}/skip"
SUBJECT=""
CHECK=""
MAIL=""
COMMAND=""
FROM=""
DATI=`date +%Y-%m-%d-%H-%M-%S`
SEND_LIST=""
MN=0

USAGE()
{
  echo "Usage: ${PGM} <options>"
  echo "  Version: ${VER}"
  echo "  options               :"
  echo "    -h | --help         : this help"
  echo "    -f | --from         : From"
  echo "    -s | --subject      : Subject"
  echo "    -V                  : Version"
  echo "    -x                  : set -x"
}
if [ ${#} -lt 1 ]; then
  echo "  Do NOT know what to do. Exiting ..."
  USAGE
  exit 1
fi
while [ ${#} -ge 1 ]
  do
  case ${1} in
    -f | --from) FROM="${2}"; shift ;;
    -h | --help) USAGE; exit 1 ;;
    -s | --subject) SUBJECT="${2}"; shift ;;
    -V) echo "${PGM}: v${VER}"; exit 2 ;;
    -x)  set -x ;;
    *)  echo "Option ${1} not known."; USAGE; exit 1 ;;
  esac
    shift
done

echo "`date` ${PGM} v${VER} started."|tee -a ${LOG}
echo "  FROM=${FROM}|" |tee -a ${LOG}
echo "  SUBJECT=${SUBJECT}|" |tee -a ${LOG}
touch ${TMP}

if [ ! -d ${DATA_DIR} ]; then
  mkdir ${DATA_DIR}
  echo "  Dir. ${DATA_DIR} created."|tee -a ${LOG}
fi
if [ ! -d ${SUBJECTS_DIR} ]; then
  mkdir -p ${SUBJECTS_DIR}
  echo "  Dir. ${SUBJECTS_DIR} created."|tee -a ${LOG}
fi
if [ ! -d ${DONE_DIR} ]; then
  mkdir -p ${DONE_DIR}
  echo "  Dir. ${DONE_DIR} created."|tee -a ${LOG}
fi
if [ ! -d ${SKIP_DIR} ]; then
  mkdir -p ${SKIP_DIR}
  echo "  Dir. ${SKIP_DIR} created."|tee -a ${LOG}
fi

# When CHECK=1, then no FROM is needed.
if [ ! ${CHECK} ] && [ "${FROM}" = "" ]; then
  echo "  NO FROM-address ($FROM}). So, no idea to answer to. Exiting ..."|tee -a ${LOG}
  exit 3
fi

# Check if " } " is in the SUBJECT. Then is COMMAND. And NOT to be stored
ANSW=`echo ${SUBJECT}|grep ':'`
# When a CMD (in ANSW) and a FROM-address
if [ "${ANSW}" != "" ] && [ "${FROM}" != "" ]; then
  COMMAND=`echo ${SUBJECT}|cut -d\: -f2|tr [:upper:] [:lower:]|sed 's/ //g'`
  echo "    COMMAND=${COMMAND}|"|tee -a ${LOG}
  case ${COMMAND} in
# ----------------
    help)
      echo "nl-fsod: <commands> " > ${TMP}
      echo "  help : this help." >> ${TMP}
      echo "" >> ${TMP}
      cat ${TMP}| mailx -s "[nl-fsod] Commands: " ${FROM}
      echo "  Mailed commands to ${FROM}"|tee -a ${LOG}
      cp /dev/null ${TMP}
    ;;
#
# ----------------
    *)
     echo "  Wrong command (${COMMAND}). Use \"nl-fsod: help\" in the subject for some help."|tee -a ${LOG}| mailx -s "[nl-fsod] Wrong command." ${FROM}
     ;;
  esac
fi

# If NO COMMAND then store


rm ${TMP}
echo "`date` ${PGM} v${VER} finished."|tee -a ${LOG}
exit 0

