#!/bin/bash

HOSTNAME=$(hostname -f)
LINE_BREAK=""

FOOTER="This message was generated by StackStorm action `basename $0` running on `hostname`"

# Allow user to provide a custom sendmail binary for more flexibility and easier
# testing
SENDMAIL_BINARY=$1

if [ "${SENDMAIL_BINARY}" = "None" ]; then
    # If path to the sendmail binary is not provided, try to find one in $PATH
    SENDMAIL=`which sendmail`

    if [ $? -ne 0 ]; then
        echo "Unable to find sendmail binary in PATH" >&2
        exit 2
    fi

    MAIL="$SENDMAIL -t"
else
    MAIL="${SENDMAIL_BINARY}"
fi
shift

if [[ $1 =~ '@' ]]; then
  FROM=$1
else
  FROM="$1@${HOSTNAME}"
fi
shift
TO=$1
shift
SUBJECT=$1
shift
SEND_EMPTY_BODY=$1
shift
CONTENT_TYPE=$1
shift
BODY="$1"
shift
IFS=',' read -ra ATTACHMENTS <<< "$@"

if [[ -z $ATTACHMENTS ]]; then
  ATTACHMENTS=""
fi

if [[ "${CONTENT_TYPE}" = "text/html" ]]; then
  LINE_BREAK="<br><br>"
else
  LINE_BREAK=""
fi

get_mimetype(){
  # warning: assumes that the passed file exists
  file --mime-type "$1" | sed 's/.*: //'
}

trimmed="${BODY// }"
if [[ -z $trimmed && $SEND_EMPTY_BODY -eq 1 ]] || [[ -n $trimmed ]]; then

{

cat <<EOF
TO: ${TO}
FROM: ${FROM}
SUBJECT: =?UTF-8?B?$(echo ${SUBJECT} | base64 -w 0)?=
EOF

if [[ -n $ATTACHMENTS ]]; then

  boundary="ZZ_/afg6432dfgkl.94531q"

  cat <<EOF
Content-Type: multipart/mixed; boundary="${boundary}"

EOF

  for file in "${ATTACHMENTS[@]}"; do
    [ ! -f "$file" ] && echo "Warning: attachment ${file} not found, skipping" >&2 && continue

    mimetype=$(get_mimetype "$file")

    cat <<EOF
--${boundary}
Content-Type: ${mimetype}
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="$(basename $file)"

EOF

    base64 "$file"
    echo
  done

  cat <<EOF
--${boundary}
Content-Type: ${CONTENT_TYPE}; charset=UTF-8
Content-Transfer-Encoding: 7bit
Content-Disposition: inline

EOF

else

  cat <<EOF
Content-Type: ${CONTENT_TYPE}; charset=UTF-8

EOF

fi

  cat <<EOF
${BODY}
${LINE_BREAK}
${FOOTER}

EOF

if [[ -n $ATTACHMENTS ]]; then

  cat <<EOF
--${boundary}--
EOF

fi

} | ${MAIL}

fi

if [ $? -ne 0 ]; then
  echo "Failed to send mail to ${TO}"
  exit 2
elif [[ -z $trimmed && $SEND_EMPTY_BODY -eq 0 ]]; then
  echo "Nothing to send"
  exit 0
else
  echo "Successfully sent mail to ${TO}"
  exit 0
fi
