#!/bin/sh
#
# This script opens a telnet sessoin with a MultiModem
# Cell Modem and sends the proper AT Modem Commands to
# get the mode's signal strength. The format for this
# command is:
#
# GetSignalStrength HOST PORT {LOGIN} {PSWD} {FILENAME}
#
# If no filename is given, the results are appended to
# the file CellModemTelnet.txt in the local directory.
# 
# If no LOGIN is given, it is assumed that the telnet 
# session does not require a login/password.

ModemSequence() {

	if [ -n $1 ]
	then
		echo $1
		sleep 0.1
		echo $2
		sleep 1
	fi

	echo -e "\r"
	sleep 1
	
	echo -e "display mobile\r"
	sleep 1
}

HOST="$1"
PORT="$2"

if [ $# == 3 ]
then
	FILENAME="$3"
	if [ -z "$FILENAME" ]
	then
		FILENAME=CellModemTelnet.txt
	fi
else
	LOGIN="$3"
	PSWD="$4"

	FILENAME="$5"
	if [ -z "$FILENAME" ]
	then
		FILENAME=CellModemTelnet.txt
	fi
fi

echo -e "\n----------------\n" >> $FILENAME
date >> $FILENAME

(sudo ping -c1 -w1 $HOST > /dev/null) || exit 1 

echo "Starting telnet session with" $HOST ":" $PORT >> $FILENAME

if [ $# == 3 ]
then
	ModemSequence | telnet $HOST $PORT >> $FILENAME
else
	ModemSequence $LOGIN $PSWD | telnet $HOST $PORT >> $FILENAME
fi

# Find last signal strength result

dBm=$(fgrep "Signal Strength 1xRTT" $FILENAME | tail -1 | cut -d \( -f 2 | cut -d \) -f 1 | cut -d \d -f 1)

if [ $dBm -ne 0 ]
then 

	bars=$(fgrep "Signal Strength 1xRTT" $FILENAME | tail -1 | cut -d \: -f 2 | cut -d \( -f 1 | cut -d \o -f 1)

	echo -e "\n*************************" >> $FILENAME
	echo -n "Signal Strength: " >> $FILENAME 
	echo $bars "bars" >> $FILENAME
	echo "*************************" >> $FILENAME
else
	echo -e "\nNot valid" >> $FILENAME
	exit 2
fi
