#!/bin/bash
#
# Simple call generator which uses Asterisk (www.asterisk.org)
# to generate calls.
#
# Author: Michael Manousos <manousos@inaccessnetworks.com>
# Copyright (c) 2004, Michael Manousos
#
# This program is free software, distributed under the terms of
# the GNU General Public License.
#
# $Id: callgenerator.sh,v 1.3 2004/05/27 12:15:24 manousos Exp $
#

#
# Parameters of the call generator
#
CALLFILE=""
CALLSPOOL=""
CALLMINW=""	# In seconds
CALLMAXW=""	# In seconds

NO_ARGS=0
if [ $# -eq "$NO_ARGS" ]	# Script invoked with no command-line args?
then
	echo "Usage: `basename $0` [-fs12]"
	echo "    -f  The call file to use."
	echo "    -s  The Asterisk call spool directory."
	echo "    -1  The minimum time in seconds to wait before initiating a call."
	echo "    -2  The maximum time in seconds to wait before initiating a call."
	exit 1
fi

#
# Get options from command line
#
while getopts ":f:s:1:2:v" option
do
	case $option in
	f )
		CALLFILE=$OPTARG
		;;
	s )
		CALLSPOOL=$OPTARG
		;;
	1 )
		CALLMINW=$(($OPTARG))
		;;
	2 )
		CALLMAXW=$(($OPTARG))
		;;
	esac
done

#echo "Call file: $CALLFILE"
#echo "Spool directory: $CALLSPOOL"
#echo "Minimum time: $CALLMINW second(s)"
#echo "Maximum time: $CALLMAXW second(s)"

#
# Do some parameters checking
#
if [ -z "$CALLFILE" ]; then
	echo "No call file?"
	exit 1
else
	if [ ! -f $CALLFILE ]; then
		echo "Call file '$CALLFILE' does not exist."
		exit 1
	fi
fi
if [ -z "$CALLSPOOL" ]; then
	echo "No call spool directory?"
	exit 1
else
	if [ ! -d "$CALLSPOOL" ]; then
		echo "Call spool directory '$CALLSPOOL' does not exist."
		exit 1
	fi
fi
if [ -z "$CALLMINW" ]; then
	echo "No min call waiting time?"
	exit 1
fi
if [ -z "$CALLMAXW" ]; then
	echo "No max call waiting time?"
	exit 1
fi
if [ $CALLMINW -gt $CALLMAXW ]; then
	echo "Inappropriate values for min and max call waiting times."
	exit 1
fi

CALLNO="1"
RANDMAX="32767"
RANDOP=$((RANDMAX/CALLMAXW))
TIME="0"
CPS="0"
CPS_STRING="-"
while [ 1 ]
do
	# Get a random number between CALLMINW...CALLMAXW
	# Note: Use bash's RANDOM variable (generates a random between 0...32767)
	# Note: If the limits have the same value, always return that value
	if [ $CALLMAXW -eq $CALLMINW ]; then
		RES=$CALLMAXW
	else
		while [ 1 ]
		do
			RAND=$RANDOM
			RES=$((RAND/RANDOP))
			if [[ $RES -ge $CALLMINW ]]; then
				if [[ $RES -le $CALLMAXW ]]; then
					break
				fi
			fi
		done
	fi

	# Generate a call after a random time interval
	echo "[Call $CALLNO, Time $TIME, CPS $CPS_STRING] Waiting $RES second(s)..."
	sleep $RES
	cp -f "$CALLFILE" "$CALLSPOOL/callgen$RANDOM$RANDOM"

	# Update stuff
	CALLNO=$((++CALLNO))
	TIME=$((TIME+RES))
	CPS=$((CALLNO*100/TIME))
	CPS_STRING=$((CPS/100)).$(($((CPS%100))/10))$(($((CPS%100))%10))
done

