#!/usr/bin/env bash

script_name="$(basename $(realpath $0))"
working_dir="$(dirname $(realpath $0))"

LOCK_DIR="/tmp/$(basename $0).$$.LOCK"

conf_file="${working_dir}/conf/$1"

# ----------
# Base Function(s)
# ----------


usage() {


   [[ -n  "$1" ]] && error "$1"


   [[ $terminal ]] && echo -e "
\033[1mUsage:\033[m

   $(basename $0) <name-of-the-configuration-file>

\033[1mDescription\033[m

   Script sends a (short) E-Mai. Recipient(s), Sender, Message and Mail-Body
   must be defined in a configuration file placed in subdirectory 'conf' of
   the directory where the script itself lives.

\033[1mOptions\033[m

   Only an required Option is the name of the configuration file.

\033[1mFiles\033[m

   Configuration file placet in directory '$working_dir'.

\033[1mExample:\033[m
   
   Send an reminder E-Mail

      $(basename $0) reminder_email-protocol.conf

"

   clean_up 1

}


clean_up() {

   # Perform program exit housekeeping
   rm -rf "$LOCK_DIR"
   blank_line
   exit $1

}

echononl(){
   if $terminal ; then
      echo X\\c > /tmp/shprompt$$
      if [ `wc -c /tmp/shprompt$$ | awk '{print $1}'` -eq 1 ]; then
         echo -e -n "   $*\\c" 1>&2
      else
         echo -e -n "   $*" 1>&2
      fi
      rm /tmp/shprompt$$
   fi
}

warn (){
   if $LOGGING || $terminal ; then
      echo ""
      if $terminal ; then
         echo -e "   [ \033[33m\033[1mWarn\033[m ]  $*"
      else
         echo "   [ Warn ]  $*"
      fi
      echo ""
   fi
}

fatal(){
   echo ""
   if $terminal ; then
      echo -e "   [ \033[31m\033[1mFatal\033[m ] $*"
   else
      echo -e "   [ Fatal ] $*"
   fi
   echo ""
   if $terminal ; then
      echo -e "             \033[1mScript terminated\033[m.."
   else
      echo -e "             Script terminated.."
   fi
   echo ""
   rm -rf $LOCK_DIR
   exit 1
}


error (){
   echo ""
   if $terminal ; then
      echo -e "   [ \033[31m\033[1mError\033[m ] $*"
   else
      echo "   [ Error ] $*"
   fi
   echo ""
}

echo_done() {
   if $terminal ; then
      echo -e "\033[75G[ \033[32mdone\033[m ]"
   fi
}
echo_failed(){
   if $terminal ; then
      echo -e "\033[75G[ \033[1;31mfailed\033[m ]"
   fi
}

trim() {
    local var="$*"
    var="${var#"${var%%[![:space:]]*}"}"   # remove leading whitespace characters
    var="${var%"${var##*[![:space:]]}"}"   # remove trailing whitespace characters
    echo -n "$var"
}

blank_line() {
   if $terminal ; then
      echo ""
   fi
}


# ----------
# - Jobhandling 
# ----------

# - Run 'clean_up' for signals SIGHUP SIGINT SIGTERM
# -
trap clean_up SIGHUP SIGINT SIGTERM

# - Create lock directory '$LOCK_DIR"
#
mkdir "$LOCK_DIR"


# ----------
# - Some checks ..
# ----------

# - Running in a terminal?
# -
if [[ -t 1 ]] ; then
   terminal=true
else
   terminal=false
fi


# ----------
# - Read commandline parameter
# ----------

while getopts bh opt ; do
   case $opt in
      h)    usage
            ;;
      \?)   usage ;;
   esac
done

[[ $# -ne "1" ]] && usage "Wrong number of arguments"


# ==========
# - Begin Main Script
# ==========

# ----------
# - Headline
# ----------

if $terminal ; then
   echo ""
   echo -e "\033[1m----------\033[m"
   echo -e "\033[32m\033[1mRunning script \033[m\033[1m$script_name\033[32m .. \033[m"
   echo -e "\033[1m----------\033[m"
fi



# ----------
#  Read Configurations from $conf_file
# ----------

blank_line

# - Give your default values here
# -
LOGGING=false
BATCH_MODE=false

echononl "Read in configuration file.."
if [[ -f "$conf_file" ]]; then
   source "$conf_file"
   if [[ $? -eq 0 ]]; then
      echo_done
   else
      echo_failed
      error "Error reading configuration file '$conf_file'."
      clean_up 1
   fi
else
   echo_failed
   fatal "No configuration file '$conf_file' present!"
fi

[[ -z "$(trim $EMAIL_FROM)" ]] && fatal "No sender address given!"
[[ -z "$(trim $EMAIL_ADDRESSES)" ]] && fatal "No recipient address given!"
[[ -z "$(trim $SUBJECT)" ]] && fatal "Missing subject!"
[[ -z "$(trim $MESSAGE)" ]] && fatal "Missing mail body (var 'MESSAGE')!"


if [[ "$(date +%A)" != "$DAY" ]] ; then
   warn "Wrong day
             \033[1mNo e-mail was sended.\033[m"
   clean_up 1
fi


# - Save content of variables 'MESSAGE' and 'SUBJECT' temporarily to
# - a file, in order to convert them to the appropriate charset
# -
echo "$MESSAGE" > ${LOCK_DIR}/message_tmp.txt
echo "$SUBJECT" > ${LOCK_DIR}/subject_tmp.txt


# =====
# - Send E-Mail using ISO-8859-15 Charset
# =====

# - Convert to ISO-8859-15
# -
#iconv -t ISO-8859-15 -o ${LOCK_DIR}/subject_tmp_ISO-8859-15.txt ${LOCK_DIR}/subject_tmp.txt
#iconv -t ISO-8859-15 -o ${LOCK_DIR}/message_tmp_ISO-8859-15.txt ${LOCK_DIR}/message_tmp.txt

# - encode base64
# -
#ENCODED_SUBJECT="=?iso-8859-15?B?$(cat ${LOCK_DIR}/subject_tmp_ISO-8859-15.txt | base64 --wrap=0)?="
#ENCODED_MESSAGE="$(cat ${LOCK_DIR}/message_tmp_ISO-8859-15.txt | base64)"
#content_type='Content-Type: text/plain;\n charset="iso-8859-15"'
#transfer_encoding='Content-Transfer-Encoding: base64'
#content_disposition='Content-Disposition: inline'

# - encode quoted-printable
# -
#ENCODED_SUBJECT="=?iso-8859-15?Q?$(cat ${LOCK_DIR}/subject_tmp_ISO-8859-15.txt | qprint -e)?="
#ENCODED_MESSAGE="$(qprint -e ${LOCK_DIR}/message_tmp_ISO-8859-15.txt)"
#content_type='Content-Type: text/plain;\n charset="iso-8859-15"'
#transfer_encoding='Content-Transfer-Encoding: quoted-printable'
#content_disposition='Content-Disposition: inline'


# =====
# - Send E-Mail using UTF-8 Charset
# =====

# - Convert to UTF-8
# -
iconv -t UTF8 -o ${LOCK_DIR}/subject_tmp_UTF8.txt ${LOCK_DIR}/subject_tmp.txt
iconv -t UTF8 -o ${LOCK_DIR}/message_tmp_UTF8.txt ${LOCK_DIR}/message_tmp.txt

# - encode base64
# --
ENCODED_SUBJECT="=?utf-8?B?$(cat ${LOCK_DIR}/subject_tmp_UTF8.txt | base64  --wrap=0)?="
ENCODED_MESSAGE="$(cat ${LOCK_DIR}/message_tmp_UTF8.txt | base64)"
content_type='Content-Type: text/plain;\n charset="utf-8"'
transfer_encoding='Content-Transfer-Encoding: base64'
content_disposition='Content-Disposition: inline'

# - quoted-printable
# -
#ENCODED_SUBJECT="=?utf-8?Q?$(cat ${LOCK_DIR}/subject_tmp_UTF8.txt | qprint -e)?="
#ENCODED_MESSAGE="$(qprint -e ${LOCK_DIR}/message_tmp_UTF8.txt)"
#content_type='Content-Type: text/plain;\n charset="utf-8"'
#transfer_encoding='Content-Transfer-Encoding: quoted-printable'
#content_disposition='Content-Disposition: inline'



# - If you know the Charset of the String variable 'SUBJECT' and 'MESSAGE', and
# - saying it is 'UTF-8', then you can user these variables directly:
# - 
#ENCODED_SUBJECT="=?utf-8?B?$(base64 --wrap=0 <<< "${SUBJECT}")?="
#ENCODED_MESSAGE="$(base64 <<< "${MESSAGE}")"
#content_type='Content-Type: text/plain;\n charset="utf-8"'
#transfer_encoding='Content-Transfer-Encoding: base64'
#content_disposition='Content-Disposition: inline'



blank_line
for EMAIL_TO in $EMAIL_ADDRESSES ; do 

	echononl "Send reminder e-mail to $EMAIL_TO .."
   echo -e "From: ${EMAIL_FROM}
To: ${EMAIL_TO}
Subject: ${ENCODED_SUBJECT}
${content_type}
${transfer_encoding}
${content_disposition}

$ENCODED_MESSAGE
" | /usr/sbin/sendmail -F "$(whoami)" -f $EMAIL_FROM  $EMAIL_TO

   if [[ $? -ne 0 ]]; then
		echo_failed
   else
		echo_done
	fi
done
blank_line

clean_up 0
