#!/bin/bash
# Send an email notification whenever someone pushes an update to rsyncd.

# Default configuration.
# This can be overridden in /etc/default/notify-rsync-upload.
EMAIL_FROM="\"Server: ${HOSTNAME%%.*}\" <noreply@slackware.uk.net>"
EMAIL_TO=("Systems' Administrator <sysadmin@slackware.uk>")
LOGSDIR="/var/log/duplication/rsync-uploads"

# Read /etc/default/notify-rsync-upload if it exists.
[[ -e /etc/default/notify-rsync-upload ]] && {
  # shellcheck disable=SC1091
  source /etc/default/notify-rsync-upload || {
    printf "%s: %s\\n" "${0##*/}" "failed reading /etc/default/notify-rsync-upload" >&2
    exit 1
  }
}

# Make sure the logs directory exists.
mkdir -p "$LOGSDIR" 2>/dev/null || {
  printf "%s: %s\\n" "${0##*/}" "Failed to create logs directory" >&2
  exit 1
}

# Update the log with this upload date/time.
printf "%s - %s\\n" "$(printf "%(%c)T")" "${RSYNC_USER_NAME:-(none)}@${RSYNC_HOST_NAME:-$RSYNC_HOST_ADDR}" >>"$LOGSDIR/${RSYNC_MODULE_NAME%%-upload}"

# Determine the subject of the message.
if (( RSYNC_EXIT_STATUS == 0 )); then
  EMAIL_SUBJECT="Upload success: ${RSYNC_MODULE_NAME%%-upload}"
elif (( RSYNC_EXIT_STATUS == -1 )); then
  EMAIL_SUBJECT="Upload error: ${RSYNC_MODULE_NAME%%-upload}"
else
  EMAIL_SUBJECT="Upload failure: ${RSYNC_MODULE_NAME%%-upload}"
fi

# Send the message.
if [[ -n "$EMAIL_FROM" ]] && (( "${#EMAIL_TO[@]}" != 0 )); then
  printf "%s:\\t%s\\n%s:\\t\\t%s\\n%s:\\t%s\\n%s:\\t\\t%s\\n" "Auth'd user" "$RSYNC_USER_NAME@$RSYNC_HOST_NAME [$RSYNC_HOST_ADDR]" "Module" "$RSYNC_MODULE_NAME ($RSYNC_MODULE_PATH)" "Exit code" "$RSYNC_EXIT_STATUS" "PID" "$RSYNC_PID" | mail -r "$EMAIL_FROM" -s "$EMAIL_SUBJECT" "${EMAIL_TO[@]}" >/dev/null 2>&1 || {
    printf "%s: %s\\n" "${0##*/}" "mail command failed" >&2
    exit 1
  }
else
  printf "%s: %s\\n" "${0##*/}" "no sender and/or recipient configured for mail delivery" >&2
  exit 1
fi

exit 0
