#!/bin/bash

# Default configuration.
CHECK_DIRS=('/')
EMAIL_TO=('sysadmin@slackware.uk')
EMAIL_FROM="\"Server: ${HOSTNAME%%.*}\" <noreply@slackware.uk>"

# Allow /etc/default/warn-git-status to override default configuration.
[[ -e /etc/default/warn-git-status ]] && {
  # shellcheck disable=SC1091
  source /etc/default/warn-git-status || {
    printf "%s: %s\\n" "${0##*/}" "failed reading /etc/default/warn-git-status" >&2
    exit 1
  }
}

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 message.
if [[ -n "${EMAIL_TO[*]}" ]]; then
  if hash mailx >/dev/null 2>&1; then
    mailx -S "from=$EMAIL_FROM" -s "Git statuses" "${EMAIL_TO[@]}" <"$OUTPUT_FILE" 2>/dev/null || {
      printf "%s: %s\\n" "${0##*/}" "mailx command failed" >&2
      exit 1
    }
  elif hash mail >/dev/null 2>&1; then
    mail -r "$EMAIL_FROM" -s "Git statuses" "${EMAIL_TO[@]}" <"$OUTPUT_FILE" 2>/dev/null || {
      printf "%s: %s\\n" "${0##*/}" "mail command failed" >&2
      exit 1
    }
  else
    printf "%s: %s\\n" "${0##*/}" "no mailer command found" >&2
    exit 1
  fi
else
  printf "%s: %s\\n" "${0##*/}" "no recipient configured for mail delivery" >&2
  exit 1
fi

exit 0
