#! /bin/ksh
#
# ident @(#)immonitor-users	1.12 05/02/00 SMI
#
# Copyright 1998 Sun Microsystems, Inc. All Rights Reserved.
# All Rights Reserved.
#
# imta-users script
#
# Internet Mail Users Monitoring Script
# Fetches the top users of the SIMS and the targets of a spammer
#
# Best viewed with tabstop=4

PATH=${PATH}:/opt/SUNWmail/sbin:.
export PATH

PID=$$
export PID

export gettext=/usr/bin/gettext
export TEXTDOMAIN=monitor_script

SUBMTRS_FILE=/tmp/users.sub.$PID   #### Contains $8 of Log file 
RCPTS_FILE=/tmp/users.mailto.$PID  #### Contains the rcpt to:'s of -r
TOP_FILE=/tmp/users.top.$PID       #### Contains the list of submitters
MAIL_FILE=/tmp/users.mailfile.$PID #### Contains the output of the Command
SUBJ_FILE=/tmp/users.subj.$PID

# If you change the name of the file here, make the corresponding change
# inside the awk script also.

export SUBMTRS_FILE RCPTS_FILE TOP_FILE MAIL_FILE SUBJ_FILE ; 

Usage ()
{
	# L10N:
	# Translate submitter, num (number) and alert_recipients
	#
	echo `$gettext "Usage:"`
	echo "\timmonitor users { [-s submitter] [-T num] }"
	echo "\t [-r alert_recipients] [-hdv] imta_log_file\n"
	
	echo `$gettext " [-h]: Display the usage message"`
	echo `$gettext " [-d]: Display the execution steps"`
	echo `$gettext " [-v]: Run in verbose mode"`
	echo `$gettext " [-s submitter]: The fully qualified e-mail address of the submitter"`
	#
	# L10N: Dont translate IMTA
	# Here num means number
	#

	echo `$gettext " [-T num]: List the top <num> submitters of mail to this IMTA"`
	echo `$gettext " [-r alert_recipients]: A comma separated list of mail recipients to notify"`
### L10N: Dont translate SMTP
	echo `$gettext " [-A Host]: Alternate SMTP host to connect to"`
	echo
}

trap 'rm -f $SUBMTRS_FILE $RCPTS_FILE $TOP_FILE $MAIL_FILE $SUBJ_FILE' 0 1 2 3 15

rm -f $SUBMTRS_FILE $RCPTS_FILE $TOP_FILE $MAIL_FILE
sflag=0; Tflag=0; rflag=0; Debug=0;

if [[ $# -lt 2 ]]
then
	Usage ;
	exit 64 ; # EX_USAGE of sysexits.h
fi

while getopts :s:T:r:A:hdv var
do
	case $var in
	s)	Submitter=$OPTARG
		export Submitter # Export needed since we'll be passing this into awk
		sflag=1 
		export sflag ;;

	T)	Number=$OPTARG
		export Number # Export needed since we'll be passing this into awk
		Tflag=1 ;;

	r)	Recpts=$OPTARG
		rflag=1 ;;

	A)  AltHost=$OPTARG  ;; # Alternate SMTP host to connect to

	d | v)	Debug=1 ;;

	: | \? | h)	Usage
		exit 64 ;;

	esac
done

shift $(($OPTIND-1))
LOGFILE=$1

if [[ -z $LOGFILE ]]
then
	echo `$gettext "Log file not specified"`
	echo 
	Usage ;
	exit 64;
fi

Validate_User () {
	uid=`/usr/xpg4/bin/id -u`
	inet_uid=`/usr/xpg4/bin/id -u inetmail`

	if [[ ($uid -ne 0) && ($uid -ne $inet_uid) ]]; then
		echo `$gettext "Permission denied. You need to be root/inetmail"`
		exit 77 ; # EX_NOPERM of sysexits.h
	fi
}

Validate_User ;

if [[ ! -f $LOGFILE ]]
then
	echo "$LOGFILE : \c"
	echo `$gettext "no such file or directory"`
	exit 66 ; # EX_NOINPUT of sysexits.h
fi

if [[ ! -r $LOGFILE ]]
then
	echo "$LOGFILE : \c"	
	echo `$gettext "permission denied"`
	exit 77 ; # EX_NOINPUT of sysexits.h
fi

export sflag Tflag rflag ;

if [[ (sflag -eq 0) && (Tflag -eq 0) ]]
then
	echo `$gettext "please specify -s OR -T options"`
	echo
	Usage ;
	exit 64 ;
fi

# nawk wont create the temp files if no matches are found. This will cause
# sort to report "File Not Found". So, create files before getting into nawk.
#

touch $SUBMTRS_FILE $RCPTS_FILE $TOP_FILE $MAIL_FILE
if [[ $Debug -eq 1 ]]; then
set -x
fi

#
# Passing the flags to nawk - Improves performance, when called with -s 
# and -T. Otherwise we may need to sort the log file twice

# nawk is used instead of awk. With nawk, environment variables can be
# accessed from within and also has -v to pass variables.

nawk -v sFlag=$sflag -v TFlag=$Tflag -v Pid=$PID '
BEGIN { 
		Submtr = ENVIRON["Submitter"] ;
		SUB_FILE = sprintf ("%s.%d", "/tmp/users.sub", Pid);
		TOP_FILE = sprintf ("%s.%d", "/tmp/users.top", Pid);
	}
{ 
	Sub_Not_Qlfd = subLog_Not_Qlfd =0;

	# subLog -> The submitters adrress as present in the logfile.

	# The Enqueued Message will have a Non-Null $7 and $8.

	if (($5 == "E") && ($3 != "reprocess") && $7 && $8 ) {

		# Dont internationalize this, file used for internal use only.

		if (TFlag == 1)
			printf "%s\n", $7 >> TOP_FILE

		if (sFlag == 1) {

			if (match (Submtr, "@") == 0) { # Not fully Qualified
				Sub=Submtr ;
				Sub_Not_Qlfd = 1;
			}

			if (match ($7, "@") == 0) {  # Not fully Qualified
				subLog_Not_Qlfd = 1;
				subLog=$7;
			}
	
			if ( (Sub_Not_Qlfd == 0) && (subLog_Not_Qlfd == 0) ) {
				# Both are fully Qualified		
				Sub=Submtr;
				subLog=$7;
			}
			else {
	
			# One of them is not fully Qualified, so we compare only
			# the usernames of the 2 addresses
	
				if (Sub_Not_Qlfd == 1) {
					Sub=Submtr;
				}
				else {
					split (Submtr, Arr, "@");
					Sub=Arr[1];
				}
					
				if (subLog_Not_Qlfd == 1) {
					subLog=$7;
				}
				else {
					split ($7, Arr, "@");
					subLog=Arr[1];
				}
			}

			# $7 - Contains submitter, $8 - recipient
	
			if (Sub == subLog) {
				if ( split ($8, recp, ";") == 2 ) ## Added for 4.0. Now the recpts
					print recp[2] >> SUB_FILE  ## are of the form rfc822;xx@yy.com
				else
					print $8  >> SUB_FILE
			}
		} # End of if ( sFlag == 1)

	} # End of if ( .... $7 !~ NULL && $8 !~ NULL ######

}' $LOGFILE 

if [[ sflag -eq 1 ]]
then

	if [[ -s $SUBMTRS_FILE ]]
	then
		sort $SUBMTRS_FILE | uniq -c | sort -rn |
			nawk -v Sub=$Submitter '
				BEGIN { 
					gettext = "/usr/bin/gettext"

					msGstr = gettext "Targets of %s:" ;
					"gettext \"Targets of %s:\" " | getline format ;
					close ("gettext \"Targets of %s:\" ") ;
					printf format, Sub ; printf "\n" ;
				}

				{ 
					printf "\t%d.\t%s\n", NR, $0 ;
			}' > $MAIL_FILE
	else
		echo `$gettext "No targets found for: "` $Submitter
	fi
fi

if [[ $Tflag -eq 1 ]]
then
	if [[ -s $TOP_FILE ]]
	then
		sort $TOP_FILE |  uniq -c | sort -rn | nawk -v Numstr=$Number '
			BEGIN { 
				gettext = "/usr/bin/gettext" ;
				Num = int (Numstr) ;

				msGstr = gettext "The top %d mail submitter(s):"
				"gettext \"The top %d mail submitter(s):\" " | getline format ;
				close ("gettext \"The top %d mail submitter(s):\" ") ;
				printf format, Num ; printf "\n" ;
			}
			{
				if (NR <= Num)
					printf "\t%d.\t%s\n", NR, $0 ;
			}

			END { if (NR < Num) {
					msGstr = gettext "Only %d unique submitter(s) found." ;
					"gettext \"Only %d unique submitter(s) found.\" " |getline format;
					close ("gettext \"Only %d unique submitter(s) found.\" ");
					printf format, NR ; printf "\n" ;
				  }
		}' >> $MAIL_FILE
	else
		echo `$gettext "No submitter(s) found"`
	fi
fi

SendMail ()
{

# Do not indent. Some of the commands to mconnect need to
# appear before any space/tab.

mconnect $1 << _EOF > /dev/null
helo `uname -n`
mail from: `/usr/xpg4/bin/id -un`
`cat $RCPTS_FILE`
data
`cat $SUBJ_FILE`

`cat $MAIL_FILE`
.
quit
_EOF

}

if [[ $rflag -eq 1 ]]
then
	# The Recpts can be comma separated mail addresses.  So we use nawk to
	# break then up and put them in a file. This is required since each of
	# the recipients to mconnect need to be specified with "rpct to:"

	echo $Recpts | nawk '{
		i=1;
		split ($0, Arr,",");
		while (Arr[i])
			printf "rcpt to: %s\n", Arr[i++]	

	}' > $RCPTS_FILE
		
	# If AltHost is not specified, localhost is used by default.

	if [[ (-s $MAIL_FILE) && (-s $RCPTS_FILE) ]]
	then

# L10N: Dont translate "Subject: ...." string,
# "Content-Type:", "charset="

		echo `$gettext "Subject: immonitor: Top users/targets of spammer"` > $SUBJ_FILE
		echo "From: SIMS Admin <`/usr/xpg4/bin/id -un`>" >> $SUBJ_FILE
		echo "MIME-Version: 1.0" >> $SUBJ_FILE

# L10N: Look up the following table and insert the charset corresponding to
# your language
# --------------------------------------------------------------------------
# English       :   US-ASCII
# --------------------------------------------------------------------------
#

		echo `$gettext "Content-Type: text/plain ; charset=US-ASCII"` >> $SUBJ_FILE
		echo `$gettext "Content-Transfer-Encoding: 8bit"` >> $SUBJ_FILE

		SendMail $AltHost
		if [[ $? -eq 0 ]]; then
			echo `$gettext "Mail sent to:-"` $Recpts
		else
			echo `$gettext "Could not send mail to :-"` $Recpts
		fi
	fi
else
	cat $MAIL_FILE
fi

exit 0;
