#!/bin/bash
# Version: 0.1.0
# Copyright (c) 2023:
#   Darren 'Tadgy' Austin <darren (at) afterdark.org.uk>
# Licensed under the terms of the GNU General Public License version 3.
#
# Send an email notification whenever someone pushes an update to rsync.
# shellcheck disable=SC2154

# Configuration.
LOGSDIR="/var/log/suplication/rsync-uploads"

# Source the mail configuration.
source /etc/mail.conf "notify-upload" 2>/dev/null || {
  printf "%s: %s\\n" "${0##*/}" "Failed to source /etc/mail.conf" >&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" "$(date)" "{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_TO[*]}" ]]; then
  mailx "${MAILX_ARGS[@]}" -S "from=$EMAIL_FROM" -s "$EMAIL_SUBJECT" "${EMAIL_TO[@]}" <<-EOF 2>/dev/null || \
      { printf "%s: %s\\n" "${0##*/}" "mailx command failed" >&2; RET=1; }
		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
		EOF
else
  printf "%s: %s\\n" "${0##*/}" "no recipient configured for mail delivery" >&2
  RET=1
fi

exit "${RET:-0}"
