#!/bin/sh

# **************************** LICENSE START ***********************************
#
# Copyright 2012 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 ************************************

#
#  This script is called from bin/mvmail (to send/encode Metview
#  mail) and from bin/mvnews (to read/decode Metview mail).
#
#  This version tries first 'bzip2' for compressing. If both compress
#  commands fail, then the mail is sent uncompressed (which can
#  produce large emails when sending e.g. GRIB data).
#
#  Note that if 'bzip2' is used,the backwards compatibility is
#  broken, i.e. 'bzip2' compressed mails can not be read with
#  older versions of this script.
#

set -e

me=`basename $0`

# extraxt the first parameter
m=$1
shift

###########################################################

case $m in

	-s)
	# sending mail - extract next three parameters
	user=$1    ; shift
	subject=$1 ; shift
	text=$1    ; shift

	[ "$subject" = "" ] && subject="none"
	[ "$user"    = "" ] && user=$LOGNAME

	cd $METVIEW_USER_DIRECTORY

	rm -f /tmp/$$.*
	MVIMPORT_TAG="@@MAIL-TAG@@ " export MVIMPORT_TAG

	# if more paramaters, extract them (these are icons)
	for n
	do
		$METVIEW_BIN/mvimport "$n" /tmp/$$.0 >/dev/null 2>&1
		grep "^$MVIMPORT_TAG" /tmp/$$.0 >> /tmp/$$.1
	done

	if [ -s /tmp/$$.1 ]   # if icons attached then tar them here
	then

		sed "s,$MVIMPORT_TAG,./," < /tmp/$$.1 | sort -u > /tmp/$$.0

		rm -f /tmp/$$.1
		x=c

##		while m=`line || true`
		while read m
		do
			[ "$m" = "" ] && break

			# build icon file and dot file names
			d=`dirname "$m"`
			b=`basename "$m"`
			a=`echo "./$d/$b"  | sed "s,//,/,g"`
			b=`echo "./$d/.$b" | sed "s,//,/,g"`

			# add icon file and dot file into a tar file
			# first round create (x=c), then add/replace (x=r)
			tar ${x}f /tmp/$$.1 "$a" "$b"
			x=r
		done < /tmp/$$.0

		# try to compress the created tar file
		bzip2 /tmp/$$.1 || true   # try 'bzip2'
		if [ -f /tmp/$$.1.bz2 ]
		then
			message=/tmp/$$.1.bz2
			printf "info: mail compressed successfully"
		else
#			gzip /tmp/$$.1 || true   # 'bzip2' failed => try 'gzip'
#			if [ -f /tmp/$$.1.gz ]
#			then
#			    message=/tmp/$$.1.gz # name ends .gz => 'gzip' succeeded
#			    printf "warning: 'bzip2' failed, using 'gzip' instead"
#			else
			    message=/tmp/$$.1     # compression failed, file should be intact
			    printf "warning: unable to compress, mail is sent uncompressed"
#			fi
		fi
	else
		message=""                        # no icons to be attached to the mail
	fi

	if [ x$OS = xaix -o x$OS = xlinux ]
	then
	  SUBJ="-s `echo MvMail:$subject | sed 's/ /-/g'`"
	else
	  SUBJ=''
	fi

###########################################################
# build the mail message and send it
(
cat <<@
Subject: $subject
@
cat $text $debug
echo
if [ "$message" != "" ]
then

cat <<@

--METVIEW-ICONS

Use menubar ('Tools' -> 'Icon Inbox ...') to extract the
attached icons.

For ECMWF users:
  In order to make this email visible in Metview you
  need to copy it into your local Mail folder called
  'MvNewsMail'. For more instructions see the
  article called "Reading Metview Mail" in the Inbox.

  If you encounter problems setting up your Metview Mail 
  please conatct the Software Applications Team.


@
# for mailing, encode binary tar file to ascii text file
uuencode $message `basename $message` ; rm -f $message
cat <<@
--METVIEW-ICONS--
@

fi
) | mail $SUBJ $user
;;

###########################################################
	-x)
	# Check for the MAIL box
	MAIL=${MAIL:=/var/spool/mail/$LOGNAME}
	if [ ! -f $MAIL ]
	then
	   echo "$me: Cannot access mail box $MAIL" 1>&2
	   exit 1
	fi

	n=`grep begin $1 | cut -f3 -d' '`
	uudecode $1              # decode back to binary tar file

	# what type of compression was used? (if any)
	mZ=`basename $n .Z`      # check for 'compress'ed file
	mbz2=`basename $n .bz2`  # check for 'bzip2'ed file
	if [ $mZ = $mbz2 ]
	then
	   cat=cat               # assume non-compressed tar file
	elif [ `basename $n` != `basename $n .Z` ]
	then
	   cat=zcat              # it is 'compressed' tar file
	else
	   cat=bzcat             # assume 'bzip2'ed tar file
	fi

	$cat < $n |  tar xf -    # uncompress + untar
	rm -f $n
esac

rm -f /tmp/$$.*
