#!/bin/bash

# **************************** LICENSE START ***********************************
#
# Copyright 2013 ECMWF and INPE. This software is distributed under the terms
# of the Apache License version 2.0. In applying this license, ECMWF does not
# waive the privileges and immunities granted to it by virtue of its status as
# an Intergovernmental Organization or submit itself to any jurisdiction.
#
# ***************************** LICENSE END ************************************

set -x 

print_err()
{
	echo ${text_ERR}  $* >> "${f_LOG}"
} 

text_ERR="Script `basename $0` FAILED> "


to=""
cc=""
subject=""
f_MESSAGE=""
f_ATTACH=""
f_LOG=""

#--------------------------------------------------------------------
# Read arguments. 
# Getopts has problems on some HP systems so we need to use this
# argument parsing techinque.
#--------------------------------------------------------------------

while [ "$1" != "" ]
do
	case "$1" in

		-t)
			to=$2
			shift
			;;
		-c)
			cc=$2
			shift
			;;
		-s)
			subject=$2
			shift
			;;
		-m)
			f_MESSAGE=$2
			shift
			;;
		-f)     
			f_ATTACH=$2
			shift
			;;
		-l)     
			f_LOG=$2
			shift
			;;
		*) 
			;;
	
	esac	
	shift
done

#-------------------------------
# Checks
#-------------------------------

if [ x"$f_LOG" = x ] ; then
	f_LOG="/dev/null"
fi

#Clear log file
> "$f_LOG"

if [ x"$to" = x ] ; then
	print_err "No email address is specified!"
   	exit 1
fi

if [ x"$subject" = x ] ; then
	subject="Metview icons"
fi

if [ x"$f_MESSAGE" != "x"  -a ! -f "$f_MESSAGE" ] ; then
	print_err "Message file does not exist!"
   	exit 1
fi

if [ x"$f_ATTACH" = x ] ; then
	print_err "No attachment is specified!"
   	exit 1
fi

if [ ! -f "$f_ATTACH" ] ; then
	print_err "Attachment file does not exist!"
   	exit 1
fi

#-----------------------------------------
# Build the mail message and send it.
#-----------------------------------------

(
if [ x"$f_MESSAGE" != "x" ] ; then 
   cat $f_MESSAGE
fi

echo 

if [ -f "$f_ATTACH" ]
then

cat << EOF
METVIEW-ICONS --------------->

This mail has been sent from Metview. The attachment is a tar.gz file containing some Metview icons (together with their descriptor files needed by Metview to interpret them). 

To import these icons into your Metview environment you need do as follows:

   1. Download the tar.gz attachment into a Metview folder 
   2. Right click on the tar.gz icon in the Metview user interface and select 'Extract'. A new Metview folder will be created for you containing all the extracted icons.

<--------------- METVIEW-ICONS

EOF
# for mailing, encode binary tar file to ascii text file
#uuencode $f_ATTACH `basename $f_ATTACH` #; rm -f $fAttach

fi
) | mail "$to" -s "$subject" -a "$f_ATTACH"

echo "Return value of mail command: " $?  

if [ -f "$f_ATTACH" ] && rm -f "$f_ATTACH"

exit 0
