#!/bin/ksh
#
# Copyright 2007 Yann Rouillard <yann@blastwave.org>
# All rights reserved.  Use is subject to license terms.
#
# Redistribution and/or use, with or without modification, is
# permitted.  This software is without warranty of any kind.  The
# author(s) shall not be liable in the event that use of the
# software causes damage.
#
# mail2maintainer - works like mail except the recipient is 
#           a package name, mail2maintainer find the real email
#	    from the package name
#

# Function : get_package_maintainer
# Purpose  : given a package name, return the maintainer name
# Arguments: the package name
# Returns  : the maintainer name
#
# TODO: find a proper way to get the maintainer
#
function get_package_maintainer
{
	_PACKAGE="$1"

	# This has to be improved. Maintainer is retrieved from the web page. It will be replaced by a sql query
	_MAINTAINER="`wget -q http://www.opencsw.org/packages/$_PACKAGE -O- | grep Maintainer | sed -e "s,.*/maintainers/\([^\'\\\"]*\).*,\1,g"`"

	# In case Maintainer string is empty, try to find the maintainer from a gspec file
	# It's a bit crappy, but it works in msot cases (but has to be replaced also)
	if [ "$_MAINTAINER" -eq "" ] ; then
		_PACKAGE="`grep bitname files/*.gspec | awk '{ print $3 }' | head -n 1`"
		_MAINTAINER="`wget -q http://www.opencsw.org/packages/$_PACKAGE -O- | grep Maintainer | sed -e "s,.*/maintainers/\([^\'\\\"]*\).*,\1,g"`"
	fi

	echo "$_MAINTAINER"
}

# Function : maintainer2mail
# Purpose  : given a maintainer name, returns his email
# Arguments: the maintainer name
# Returns  : the maintainer email
#
# TODO: find a proper way to get the email
#
function maintainer2mail
{
	_MAINTAINER="$1"
	echo "$_MAINTAINER@opencsw.org"
}

PATH=$PATH:/opt/csw/bin:/usr/sfw/bin

if [[ -z "$1" ]]; then
	cat <<EOF
Usage: mail2maintainer [mail options] package_name
Given a package name, send an email to the maintainer.
EOF
	exit 1
fi

eval PACKAGE_NAME=\$$#

MAINTAINER=`get_package_maintainer $PACKAGE_NAME`
EMAIL=`maintainer2mail $MAINTAINER`

MAIL_OPTIONS=""
while [ $# -ne 1 ]; do
	MAIL_OPTIONS="$MAIL_OPTIONS \"$1\""
	shift
done

if [ ! -n "$MAINTAINER" ] ; then
	echo "No valid maintainer for package : $PACKAGE_NAME"
	eval mailx "-s" "\"[svn] Invalid maintainer for package $PACKAGE_NAME\"" -b "william@wbonnet.net" uwatch@opencsw.org
else
	eval mailx $MAIL_OPTIONS -b "william@wbonnet.net" $EMAIL	
fi
