#!/bin/bash
# Email the status of various git repositories on the system.

# Default configuration.
# This can be overridden in /etc/default/warn-git-status.
EMAIL_FROM="\"Server: ${HOSTNAME%%.*}\" <noreply@slackware.uk.net>"
EMAIL_TO=("Systems' Administrator <sysadmin@slackware.uk>")

# Read the default configuration from /etc/default/warn-git-status.
if [[ -e /etc/default/warn-git-status ]]; then
  # shellcheck disable=SC1091
  source /etc/default/warn-git-status || {
    printf "%s: %s\\n" "${0##*/}" "failed reading /etc/default/warn-git-status" >&2
    exit 1
  }
else
  printf "%s: %s\\n" "${0##*/}" "/etc/default/warn-git-status does not exist" >&2
  exit 1
fi

# Temporary output file.
OUTPUT_FILE="/tmp/${0##*/}-$$-$RANDOM"

# Remove the OUTPUT_FILE when done.
trap 'rm -f "$OUTPUT_FILE"' EXIT

# Loop through the list and process.
for DIR in "${CHECK_DIRS[@]}"; do
  [[ ! -e "$DIR" ]] || [[ ! -d "$DIR" ]] && continue

  TMP_OUTPUT="$(cd "$DIR" && [[ "$(git rev-parse --show-toplevel)" == "$PWD" ]] && git status | grep -E -ve "^(On branch|Your branch|No commits|nothing|$)" -e "\(use")"
  [[ -n "$TMP_OUTPUT" ]] && printf "%s:\\n%s\\n\\n" "$DIR" "$TMP_OUTPUT" >>"$OUTPUT_FILE"

  unset TMP_OUTPUT
done

# If there's no output, do nothing.
[[ ! -s "$OUTPUT_FILE" ]] && {
  exit 0
}

# Send the notification message.
if [[ -n "$EMAIL_FROM" ]] && [[ -n "${EMAIL_TO[*]}" ]]; then
  mail -r "$EMAIL_FROM" -s "Git statuses" "${EMAIL_TO[@]}" <"$OUTPUT_FILE" >/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
