#!/bin/sh

#-----------------------------------------------------------
# Program : sms_users                          Host : zenobe
# Author  : Philippe Andersson
# Date    : 20/11/98
# Version : 1.3
# Notice  : (c) Les Ateliers du Heron, 1996 for Scitex Europe, S.A.
# Comment : Extract statistics from system logs for SMS subsys.
#           Count number of messages sent by each user and
#           print results on stdout.
# History :
# * 1.0 (23/10/98) : Initial release.
# * 1.1 (03/11/98) : Added handling for -f parameter.
# * 1.2 (18/11/98) : Modified the call to sort in order to get
#   the users sorted by usage, heaviest users first.
# * 1.3 (20/11/98) : Finally found the options to get the sort
#   feature right.
#-----------------------------------------------------------
# Uncomment for debugging
# set -x -v

# Variables
WORKF="/tmp/sms_log"
AWKIN="/tmp/awk_input"
TODAY=$(date +%Y%m%d)

#***********************************************************
#         CODE BEGINS - GET COMMAND LINE PARAMETERS
#***********************************************************
# Disable filename generation while parsing parameters
set -f

#---------------------------------------------Get parameters
while getopts :f: argname; do
  case ${argname} in
    f) FILESET=${OPTARG}
       ;;
    :) echo "sms_users: missing required value for -${OPTARG} parameter."
       exit 1
       ;;
    ?) echo "sms_users 1.3 - SMS Server Stats per User"
       echo " "
       echo "Usage: sms_users [-f workfile]"
       echo " "
       echo "where: -f = workfile (opt. - def. /tmp/sms_log)"
       echo " "
       exit 1
       ;;
  esac
done                                         # while getopts

# Handle additional parameters (unused here)
shift $((${OPTIND} -1))
more_args=${*}

# Re-enable filename generation
set +f

#------------------------------Check for required parameters
# no required parameter.

#----------------------------------------Validate parameters
if [ -n "${FILESET}" ]; then
  # check fileset for existence
  if [ ! -r ${FILESET} ]; then
    echo "sms_stats: the specified workfile (${FILESET}) doesn't exist."
    exit 1
  fi
  # set workfile to it
  WORKF=${FILESET}
fi

#========================================================
# First generate AWK input from workfile
if [ -s ${WORKF} ]; then
  cat ${WORKF} | grep "sender ID" | awk '{print $9}' > ${AWKIN}
else
  exit 1
fi

# Now process this through AWK to get usage for each user
cat ${AWKIN} | awk '
# Word frequencies computation - based on Gawk example
{
	freq[$1]++
}

END {
	for (user in freq)
		printf "%-15s\t%d\n", user, freq[user]
}' | sort -nr +1

# Finally do some cleanup - don't touch $WORKF
rm -f ${AWKIN}
exit 0

