#!/bin/sh
#
#
# Copyright 2016 Luca Capello <luca.capello@infomaniak.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02111-1301  USA
#
#
# This is an example script that can be hooked into reprepro
# to send an email after a .changes file is processed.
#
# All you have to do is to:
# - copy it into you conf/ directory,
# - add the following to any distribution in conf/distributions
#   you want to have emails sent for:
#Log:
# --changes mail-changes.example
# (note the space at the beginning of the second line).
#
# DEPENDENCIES: mailx


set -e


if test "x${REPREPRO_OUT_DIR:+set}" = xset ; then
	# Note: due to cd, REPREPRO_*_DIR will no longer
	# be usable. And only things relative to outdir will work...
	cd "${REPREPRO_OUT_DIR}" || exit 1
else
	# this will also trigger if reprepro < 3.5.1 is used,
	# in that case replace this with a manual cd to the
	# correct directory...
	cat "mail-accepted.example needs to be run by reprepro!" >&2
	exit 1
fi


MAIL_TO="$USER"

ACTION="$1"
CODENAME="$2"
PACKAGENAME="$3"
PACKAGEVERSION="$4"
CHANGESFILE="$5"

if [ "x$ACTION" = "xaccepted" ]; then
	MAIL_FROM="$(grep Changed-By $CHANGESFILE | \
		      sed -e 's/Changed-By/From/')"
	ARCHITECTURE="$(grep Architecture $CHANGESFILE | \
			 sed -e 's/Architecture: //')"
	MAIL_SUBJECT="Accepted $PACKAGENAME $PACKAGEVERSION ($ARCHITECTURE) into $CODENAME"
	cat "$CHANGESFILE" | \
	 mail -a "$MAIL_FROM" -s "$MAIL_SUBJECT" "$MAIL_TO"
fi


exit 0
