#!/bin/sh

FROM_NAME="B. Watson"
FROM_EMAIL="urchlay@slackware.uk"

# Usage:
# pingmaint "Maintainer Name"
# pingmaint maintainer@domain.tld

SELF=$( basename $0 )

die() {
  echo "$SELF: $@" 1>&2
  exit 1
}

source ~/sbostuff/sbostuff.sh
cdsb

interactive=yes
if [ "$1" = "-m" ]; then
  interactive=no
  shift
fi

# given a maintainer's name as args, set TO_ADDR to the email address.
# if there are more than one email address for the name, print them
# all and die.
get_email() {
  TO_ADDR=""

  TO_ADDR="$( git grep -lF "MAINTAINER=\"$*\"" '*/*/*.info' | xargs grep '^EMAIL=' | cut -d\" -f2 | sort -u | cut -d\" -f2 )"

  if [ "$( echo "$TO_ADDR" | wc -l )" -gt 1 ]; then
    if [ "$interactive" = "no" ]; then
      die "Multiple email addresses: $TO_ADDR"
    fi
    echo "Multiple email addresses: $TO_ADDR"
    echo "==> Which address to use?"
    read TO_ADDR
  fi
}

builds="$( getmaintbuilds "$@" )"

if echo "$*" | grep -q '@'; then
  TO_ADDR="$@"
else
  get_email "$@"
fi

if ! echo "$TO_ADDR" | grep -q '@'; then
  if [ "$interactive" = "no" ]; then
    die "Obfuscated address: $TO_ADDR"
  else
    echo "==> Enter unobfuscated version of: $TO_ADDR"
    read TO_ADDR
  fi
fi

tmpfile="$( mktemp $SELF.XXXXXXXXXX )"
rm -f $tmpfile

echo "To: $TO_ADDR"
cat <<EOF >$tmpfile
From: $FROM_NAME <$FROM_EMAIL>
Subject: builds on SlackBuilds.org

You're listed as maintainer for these builds:

$builds

It's been a while since your last update on SBo. Are you still
maintaining these?

Please let me know.
EOF

cat $tmpfile

if [ "$interactive" = "yes" ]; then
  echo
  echo "===> Press Enter to send this email, ^C to abort."
  read
fi

echo
echo "==> Sending email to $TO_ADDR"
cat $tmpfile | msmtp "$TO_ADDR"

rm -f $tmpfile
