#!/bin/sh

#-----------------------------------------------------------
# Program : sms_stats                          Host : zenobe
# Author  : Philippe Andersson
# Date    : 22/12/98
# Version : 1.7
# Notice  : (c) Les Ateliers du Heron, 1998 for Scitex Europe, S.A.
# Comment : Extract statistics from system logs for SMS subsys.
# History :
# * 1.0 (22/10/98) : Initial release.
# * 1.1 (22/10/98) : Added summary report.
# * 1.2 (23/10/98) : Added individual usage count (sms_users)
#   and monthly archiving of raw data.
# * 1.3 (27/10/98) : Script will run every day, but mail should
#   only be sent on weekday. Added code to prevent double inclusion
#   in summary file as I did for logfile.
# * 1.4 (03/11/98) : Fixed a bug in the TIMESTAMP date format.
#   expanded to allow for "at will" re-runs on specified work
#   files. Included a modification in the call to sms_users.
# * 1.5 (05/11/98) : Added pointer to /var/adm/syslog in work-
#   file generation procedure, cause all events >= "warn" will
#   be logged there.
# * 1.6 (18/12/98) : Adapted to ignore MBC connections after
#   installing version 0.32b of the server.
# * 1.7 (22/12/98) : Further refined connections count by
#   excluding the server's original pid.
#-----------------------------------------------------------
# Uncomment for debugging
# set -x -v

# Variables
ADMINS="smsmasters"                       # see /etc/aliases
TEMPF="/tmp/messages.copy"
WORKF="/tmp/sms_log"
SUMMARY="/var/adm/sms_summary"
ORIGLOG1="/var/adm/messages"
ORIGLOG2="/var/adm/syslog"
ARCHDIR="/var/adm/sms_archive"
CURARCHF="sms_$(date +%Y%m).log"
TODAY=$(date +%Y%m%d)
DATESTAMP="$(date +"%b %_d")"
DOW=$(date +%a)

# Set default value for parameters
FILESET=""
DATERST="no"

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

#---------------------------------------------Get parameters
while getopts :f:d: argname; do
  case ${argname} in
    f) FILESET=${OPTARG}
       ;;
    d) TODAY=${OPTARG}
       DATERST="yes"
       ;;
    :) echo "sms_stats: missing required value for -${OPTARG} parameter."
       exit 1
       ;;
    ?) echo "sms_stats 1.7 - SMS Server Stats"
       echo " "
       echo "Usage: sms_stats [-f workfile -d workdate]"
       echo " "
       echo "where: -f = workfile (opt. - def. automatic)"
       echo "       -d = workdate YYYYMMDD (req. iif -f present)"
       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
  # check for -d presence
  if [ ${DATERST} != "yes" ]; then
    echo "sms_stats: You have to specifiy -d when -f is used."
    exit 1
  fi
else
  # error when -d is present
  if [ ${DATERST} != "no" ]; then
    echo "sms_stats: You can't use -d without -f."
    exit 1
  fi
fi

#========================================================
# Generate workfile if required
if [ -z "${FILESET}" ]; then
  # First take a copy of the "messages" file
  if [ -s ${ORIGLOG1} -a -s ${ORIGLOG2} ]; then
    cp ${ORIGLOG1} ${TEMPF}
    cat ${ORIGLOG2} >> ${TEMPF}
  else
    exit 1
  fi

  # Now prune this temp file to keep only SMS info
  cat ${TEMPF} | grep "${DATESTAMP}" | grep sms_serv | sort > ${WORKF}
  rm -f ${TEMPF}
else
  WORKF=${FILESET}
fi

#========================================================
# count connections (except those for MBC [mailbox check])
nconn=$(cat ${WORKF} | grep -v MBC | awk '{print $5}' | sort | uniq | wc -l)

# discount from it the server's entry
nconn=$((nconn - 1))

# count successfull ones
nsucc=$(cat ${WORKF} | grep "message sent OK" | wc -l)
succp=$(bc -q << EOT_BC
scale=3
(${nsucc} / ${nconn}) * 100
EOT_BC)

# count number of timeout on waiting for free GSM instance
ntout=$(cat ${WORKF} | grep "(all GSMs busy)" | wc -l)

# Log the summary report in tabular format
# First check that it's the first time we log this data
if [ -f ${SUMMARY} ]; then
  # look for today's date
  cat ${SUMMARY} | grep ${TODAY} > /dev/null 2>&1
  if [ ${?} -eq 0 ]; then
    # prune this data
    cat ${SUMMARY} | grep -v ${TODAY} > /var/adm/sms_temp
    mv /var/adm/sms_temp ${SUMMARY}
  fi
fi
# now append to the file
echo \"$TODAY\",\"$nconn\",\"$nsucc\",\"$succp\",\"$ntout\" >> ${SUMMARY}

#========================================================
# On weekday only, build mail and send it
if [ ${DOW} != "Sat" -a ${DOW} != "Sun" ]; then
  mail -s "SMS Server Daily Stats" ${ADMINS} << EOT_MAIL
Statistics for $(date) on $(hostname).

Total connections      : ${nconn}
Messages sent OK       : ${nsucc}
Percentage successfull : ${succp} %

Failed conn. due to timeout waiting for free GSM instance : ${ntout}

Usage splitting per individual user :
$(/root/scripts/sms_users -f ${WORKF})
EOT_MAIL
fi

#========================================================
# Archive raw data for further analysis
if [ -f ${ARCHDIR}/${CURARCHF} ]; then
  # Make sure it's the first time today that we do this
  cat ${ARCHDIR}/${CURARCHF} | grep "${DATESTAMP}" > /dev/null
  if [ ${?} -eq 0 ]; then
    # Prune this data
    cat ${ARCHDIR}/${CURARCHF} | grep -v "${DATESTAMP}" > ${ARCHDIR}/temp
    mv ${ARCHDIR}/temp ${ARCHDIR}/${CURARCHF}
  fi
  # Append to it
  cat ${WORKF} >> ${ARCHDIR}/${CURARCHF}
else
  # Zip the previous one(s)
  if [ -f ${ARCHDIR}/*.log ]; then
    for i in $(ls ${ARCHDIR}/*.log); do
      gzip ${ARCHDIR}/${i}
    done
  fi
  # Create a new one
  cat ${WORKF} > ${ARCHDIR}/${CURARCHF}
fi

#========================================================
# Clean workfile and exit
rm -f ${WORKF}
exit 0

