#!/bin/bash
#
# Find a random number less then the "endvalue" by
# executing a while loop incrementing a value until a signal (^c) is received.

# Signal 1 (SIGHUP), Signal 2 (SIGINT) like a control-c, 
# Signal 3 (SIGQUIT) usually when someone hits the "quit" key,
# Signal 15 (SIGTERM) default signal sent by the kill command.

# It calculate the remainder by dividing the last counted number
# by the inputted "endvalue".

finish_up () {
	# find remainder of dividing last number by max value
	let result=($1%$2)+1
	echo " "
	echo ...and the winner is 107user$result !
}

# start main here
# check that there is one argument

if [ $# -ne 1 ]; then
	echo Usage: random endvalue
	echo Find a random number less than the endvalue,
	echo Type \^c to exit loop and get number
	exit 0
else
	END=$1
fi

COUNT=0
trap 'STOP=1; trap 1 2 3 15' 1 2 3 15
while :
do 
	let COUNT=COUNT+1
#	echo COUNT got to $COUNT
	if [ "$STOP" == "1" ]; then
	   break
	fi
done
finish_up $COUNT $END