#!/bin/bash
#  A send mobile text messages utility for Linux. 
#  Makes sending sms text messages easy with an Internet stick (3G etc.).
#  
#  Copyright 2011 Arto Jääskeläinen   
#  temp001(at)pp.inet.fi, ajaaskel(at)forum.ubuntu-fi.org
#
#  This program is free software; you can redistribute it and/or 
#  modify it under the terms of the GNU General Public License as 
#  published by the Free Software Foundation; either version 2 of the
#  License, or (at your option) any later version.
# 
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  Ver 1.00 September 25, 2011 First version
#  Ver 1.01 September 29, 2011 Fix: Modem init
#  Ver 1.02 September 30, 2011 Fix: Mute "ZUSIMR:2" 
#  Ver 1.03 October 8, 2011 Fix: Command line parameter sanity testing 
#  Ver 1.04 October 27, 2011 Fix: 1 second wait after each modem command
#  Ver 1.05 May 21, 2012 	Fix: Failure due to null message, pre-read added.  
#							New: Device detection. 
#  Ver 1.06 May 28, 2012 New: Detection of ACMx for Nokia C-series phones
# 
THIS_VER=1.06    # <--Remember to update current version number here
#
# Do not add ANY characters in front of the line above --- version control variable.
#

GET_VERSION()
#Entry none, return INSTALLED_VER 
{
if [ -e /usr/local/bin/sendmob ]; then  # Some version of chknodes utility exists ?
INSTALLED_VER=`cut -b 1-14 /usr/local/bin/sendmob | grep THIS_VER= | sed 's/[a-Z _#<='-']*//g' `
if [ -z $INSTALLED_VER ]; then   #No version number found
INSTALLED_VER=1.00
fi 
else
INSTALLED_VER=0    #No ver file found
fi
}

CONV_IN() #Returns string looking like integer
#Entry ST, return RET
{
DOTPOS=`expr index $ST '.'`       #Position of dot
ST1=`expr match $ST '\([0-9]*\)'` #All before dot
ST2=`echo ${ST:$DOTPOS}`          #All after dot
LEN_ST2=${#ST2}                   #Length after dot
if [ $LEN_ST2 != 2 ]; then        #We force always two digits
ST2=`expr $ST2 \* 10`             #FYI, no parentehsis allowed here
if [ $ST2 = 0 ]; then             #Specific case of zero
ST2=00                            #Two digits for zero, too
fi
fi
RET=$ST1$ST2                      #Concatenated string
}

INSTALL()
{
if [ $THIS_VER_IN -gt $INSTALLED_VER_IN ] ; then  		# Need to update 
	sudo cp $0 /usr/local/bin/$installname
	GET_VERSION
	ST=$INSTALLED_VER
	CONV_IN
	INSTALLED_VER_IN=$RET
	if [ $THIS_VER_IN = $INSTALLED_VER_IN ] ; then
	echo
	fgblue; echo "Installed/updated \"$installname\" utility succesfully."; fgdefault
	else
	fgred; echo "Could not install/update \"$installname\" utility."
	echo "This ver:" $THIS_VER  "installed ver: " $INSTALLED_VER;fgdefault
	fi
fi
}

UNINSTALL()
{
if ! [ -e /usr/local/bin/$installname ] ; then
fgblue; echo "Nothing to uninstall."; fgdefault; return
else
sudo rm /usr/local/bin/$installname 2>/dev/null
fi
if [ ! -e /usr/local/bin/$installname ]; then
fgblue; echo "Uninstall succesful."; fgdefault
else
fgred; echo "Could not uninstall "sendmob" utility."; fgdefault
fi
}

HELP()
{
echo
fgbold;echo "sendmob v"$THIS_VER  "--- A SMS utility for Linux using Internet stick.";fgdefault
echo "Designed for simple sending of command line sms messages."
echo "Please disable PIN enquiry of your SIM card prior to use."
echo 
echo "On first run "sendmob" will install itself to /usr/local/bin."
echo
fgbold;echo "    sendmob [dev_name] int_tel [message]";fgdefault
fgbold;echo "    sendmob [-h | --help, -u | --uninstall]";fgdefault
echo
echo "\"dev_name\"...Optional device name of mobile stick"
echo
echo "int_tel..... Destination telephone number, international form,"
echo
echo "             starts with plus sign and country code."
echo
echo "\"message\"....Optional text. No text given --->  blank message."
echo 
echo "Example:"
echo
echo "    sendmob /dev/ttyUSB0 +3584012345678 This is my first test message."
echo
echo
}

CHECK_TELNUMBER()
# International telephone number format sanity check.
# Checks that first character is "+" and after that at least 6 numbers.
{
str_to_test="$*"
telnumber_ok="false"
min_number_length=6
if [ ${str_to_test:0:1} = "+" ] ; then
non_numeric=$( echo "${str_to_test:1}" | tr -d '[0-9]' )
if [ ${#non_numeric} = 0 ] && [ ${#str_to_test} -gt $min_number_length ] ; then
telnumber_ok="true"
fi
fi
}


clearline()
{
echo -en '\r'
echo -en "\x1b[2K"
}


fgred()
{
echo -en "\x1b[31;01m"
}

fgblue()
{
echo -en "\x1b[34;01m"
}

fgblack()
{
echo -en "\x1b[30;01m"
}

fgbold()
{
echo -e "\x1b[1m"
}

fgdefault()
{
tput sgr0
}

get_dev_name()
{
dev_name=$(ls /dev/tty[UA][SC][BM]* 2>/dev/null | sort | grep -E -m1 /dev/tty)	
}	


# Main ------------------------------------------------------

allparams=$*
numparms=$#   
installname="sendmob"
message=""
usinggivendev="false"

#Version/update control -------------------------------------
GET_VERSION
ST=$INSTALLED_VER
CONV_IN
INSTALLED_VER_IN=$RET
ST=$THIS_VER
CONV_IN
THIS_VER_IN=$RET
if ! [[ $1 = "-u" || $1 = "--unistall" ]] ; then 
INSTALL
fi
#-------------------------------------------------------------

if [ $numparms = "0" ] ; then
echo;fgred; echo "***"$installname" error:  At least telephone number expected.";fgdefault;HELP; exit 255
fi


case $(echo ${allparams:0:1}) in
+  )
 	telnumber=$(echo $allparams | cut -d " " -f1) 
	CHECK_TELNUMBER $telnumber
	if ( [ "$telnumber_ok" = "true" ] && [ $numparms -gt "1" ] ); then
	message=$(echo $allparams | cut -d " " -f2-999)	#Format telnum + [message] 
	fi		 
  	;;
- )
  	case $(echo $allparams | cut -d " " -f1) in
		-h | --help )
  		HELP;exit 0 ;;
		-u | --uninstall )
  		UNINSTALL;exit 0 ;;
		-v | --version )
  		echo 'sendmob' v$THIS_VER;exit 0
		;;
		esac
  	;;
/  )
  	givendev=$(echo $allparams | cut -d " " -f1)
	if ! ( [ "${givendev:0:5}" = "/dev/" ] && [ ${#givendev} -gt 5 ] ) ; then
	echo;echo;fgred; echo "***"$installname" error:  Invalid device name.";fgdefault;HELP; exit 255
	fi
	if ! [ -e "$givendev" ] ; then
	fgred; echo;echo "***"$installname" error:  Device does not exist."; echo; fgdefault; exit 1 
	fi    
	mobiledev=$givendev
	telnumber=$(echo $allparams | cut -d " " -f2)
	message=$(echo $allparams | cut -d " " -f3-999)   #Format device + telnum + [message]
	usinggivendev="true"
	;;
* )
echo;fgred; echo "***"$installname" error:  At least telephone number expected.";fgdefault;HELP; exit 255
  ;;
esac

#-------------------------------------------------------------
 
CHECK_TELNUMBER $telnumber
if [ "$telnumber_ok" = "false" ] ; then
echo;echo;fgred; echo "***"$installname" error:  Invalid telephone number.";fgdefault;HELP; exit 2  #Wrong telephone number format
fi
if [ "$usinggivendev" = "false" ]; then  #Scan for device 
get_dev_name
	if [ -z "$dev_name" ]; then
	fgred; echo "***$installname error: Automatic device search cannot find mobile device."; fgdefault 
	echo "Check the device is connected and ready."
	echo "Try manually given device name if detection persistently fails."
	exit 255
	fi
mobiledev=$dev_name
fi
if [ -z "$message" ]; then 
message=$HOSTNAME		#Default message
fi
cat $mobiledev >/dev/null & 
cat_pid=$!
echo -e 'ATE0r\n' >$mobiledev
sleep 1
echo -e 'AT+CPMS?\r\n' >$mobiledev
sleep 1
echo -e 'AT+CMGF=1\r\n' >$mobiledev
sleep 1
echo -e AT+CMGS='"'$telnumber'"',145'\r\n' >$mobiledev
sleep 1
echo -e "$message" >$mobiledev
sleep 1
echo -e "\x1a" >$mobiledev
sleep 5
kill $cat_pid
#----------------------------------------------------------------



