#!/bin/bash 
###############################################################################
#	SENDSMS   --  Script to send sms by 'gnokii'
#   Author : Gabriele Zappi - Rimini <gzappi@inwind.it>
#  	History:
#	  feb 17, 2001         Script created (v1.0)
#         jun  3, 2003         Use --getphonebook instead of --getmemory
#                              as changed in gnokii (Ville Skytta)
#         jan 20, 2004         Use www.gnokii.org as a primary site to get
#                              gnokii (Pawel Kot)
#                              Remove notice on mygnokii as this is no longer
#                              maintained (Pawel Kot)
#         may  6, 2007         Give a choice between SIM and phone memory for
#                              the phonebook (Pawel Kot)
#         jan 23, 2009         Remove outdated notice about pre releases
###############################################################################
# G N O K I I
#
# A Linux/Unix toolset and driver for the mobile phones.
#
# This file is part of gnokii.
#
# Gnokii is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2
# as published by the Free Software Foundation.
#
# Gnokii 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.
#
# You should have received a copy of the GNU General Public License
# along with gnokii; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Copyright (c) 2001 Gabriele Zappi - Rimini
#
###############################################################################
# $Id$
###############################################################################
# PROGNAME=`basename $0`

# var settings.

PROGNAME=${0##*/}
VERSION="1.03"
GNOKII=${GNOKII:-gnokii}
PID=$$
SMSDIR=${SMSDIR:-$HOME/tmp/sms}
TMP=~/tmp/SMStmp.$PID
BACKTITLE="SENDSMS V$VERSION"
AUTHOR="Gabriele Zappi - Rimini <gzappi@inwind.it>"

help() {
echo "$PROGNAME: $BACKTITLE - A gnokii interface for sending SMS."
echo "Written by $AUTHOR"

echo -e "\
\n\
Usage: $PROGNAME [OPTION]...\n\
\n\
Examples:\n\
  $PROGNAME                 # simply run $PROGNAME in standard mode\n\
  $PROGNAME --simulate      # Simulates. doesn't really send sms (for debug)\n\
  echo \"Hello Beauty ;-)\" | $PROGNAME --smsset\n\
                          # Preset \"Hello Beauty ;-)\" as SMS message.\n\
  $PROGNAME --smsset < mymessage.txt\n\
                          # Preset contents of file mymessage.txt \n\
                            as SMS message.\n\
  $PROGNAME --version       # Display version, author and quits.\n\
\n\
NOTE:\n\
If you require to pickup number from phone's memory (or from SIM card),\n\
for the first time, it anyway reads phonebook from your mobile phone. \n\
(It may take a while... please, be patient ;-) \n\
\n\
Available options:\n\
  --debug, -D            May bother with more debugging messages ;-)\n\
                         For debugging purpose.\n\
  --simul[ate], -S       Simulation mode. Doesn't really send SMS by phone. \n\
                         Only simulates. For debugging purpose.\n\
  --forceSMread, -s      Forces $PROGNAME to read phonebook from SIM card,\n\
                         and to parse the generated file in order to update\n\
                         the numbers' list (useful only if required to pickup\n\
                         number from the phone's memory). see NOTE.\n\
  --forceMEread, -m      Forces $PROGNAME to read phonebook from phone memory,\n\
                         and to parse the generated file in order to update\n\
                         the numbers' list (useful only if required to pickup\n\
                         number from the phone's memory). see NOTE.\n\
  --skipgnokiicheck, -K  Skip the test of the presence of binary 'gnokii'.\n\
                         (It must be somewhere in your \$PATH). It allows you\n\
                         to try this script program, even if you don't have\n\
                         'gnokii' already. ;)\n\
  --smsset, --setsms     Allows you to preset a SMS message from STDIN. (pipe\n\
                         or input redirection).\n\
                         This message will be proposed on the 'SMS message'\n\
                         field during the program input cycle.\n\
  --help, -h, /h         display this help and exit\n\
  --version, -V          output version information and exit"
echo 
exit 0
}

acex()
{
	rm -rf $TMP >/dev/null 2>&1
	clear
	exit $1
}

parse_stdin() {
	# Switch initialization
	SW_DEBUG=no
	SW_SIMUL=no
	SW_FORCEMREAD=no
	SW_SKIPGNOKITST=no
	SW_PRESETSMS=no
	PRESETSMS=""

	while [ -n "$1" ] 
	do
		case "$1" in 
			--help|-h|/h)
					help
					;;
			--version|-V)
					echo
					echo "$BACKTITLE - A gnokii interface for sending SMS."
					echo "Written by $AUTHOR"
					echo
					exit 0
					;;
			--simul*|-S)
					SW_SIMUL=yes
					;;
			--debug*|-D)
					SW_DEBUG=yes
					SW_SIMUL=yes
					;;
			--forceSMread|-s)
					SW_FORCESMREAD=yes
					;;
			--forceMEread|-m)
					SW_FORCEMEREAD=yes
					;;
			--skipgnokiicheck|-K)
					SW_SKIPGNOKITST=yes
					;;
			--smsset|--msgset|--setsms)
					SW_PRESETSMS=yes
					# will read from stdin
					echo "reading sms from stdin .."
					PRESETSMS=`cat`
					;;
			*)
					echo "$PROGNAME: Invalid parameter: "
					help
					;;
		esac
		shift
	done
}

sure_to_quit() {
 dialog --backtitle "$BACKTITLE" \
											--yesno "Really sure to quit? " 6 50
 if [ $? -eq 0 ]; then
 acex 0
 fi
}

SMS_phonereadSM() {
dialog --backtitle "$BACKTITLE" --infobox "Reading phonebook from SIM\n         Please wait" 4 40 
$GNOKII --getphonebook SM 1 end --raw > $SMSDIR/.SMlist.temp 2>/dev/null
}

SMS_phonereadME() {
dialog --backtitle "$BACKTITLE" --infobox "Reading phonebook from phone memory\n         Please wait" 4 40 
$GNOKII --getphonebook ME 1 end --raw > $SMSDIR/.MElist.temp 2>/dev/null
}

SMS_choicefrommem() {
	# read from phonebook.
	if [ "$SW_FORCESMREAD" = "yes" ] ; then
		readsim=1
	elif [ -s $SMSDIR/.SMlist.sim ]; then
		dialog --backtitle "INSERT NUMBER(s).." \
					 --yesno "SIM phonebook file is already present. \
                    Do you want to read SIM card anyway?" 8 60
		if [ $? -eq 0 ] ; then
			readsim=1
		else
			readsim=0
		fi
	else
		readsim=0
	fi
	if [ "$SW_FORCEMEREAD" = "yes" ] ; then
		readme=1
	elif [ -s $SMSDIR/.MElist.mem ]; then
		dialog --backtitle "INSERT NUMBER(s).." \
					 --yesno "Phonebook file is already present. \
                    Do you want to read phone memory anyway?" 8 60
		if [ $? -eq 0 ] ; then
			readme=1
		else
			readme=0
		fi
	else
		readme=0
	fi

	# by default read from SIM memory
	if [ $readsim -eq 0 ] && [ $readme -eq 0 ] && [ ! -s $SMSDIR/.PBKlist ]; then
		readsim=1
	fi

	SMERROR=0
	if [ $readsim -eq 1 ] ; then
		SMS_phonereadSM
		if [ $? -ne 0 ] ; then
			dialog --backtitle "INSERT NUMBER(s).." \
						 --msgbox "ERROR during reading memory the SIM card... \
	                      Insert manually destination number." 8 60
			SMERROR=1
		else
			mv -f $SMSDIR/.SMlist.temp $SMSDIR/.SMlist.sim
		fi
	else
		SMERROR=1
	fi

	MEERROR=0
	if [ $readme -eq 1 ]; then
		SMS_phonereadME
		if [ $? -ne 0 ] ; then
			dialog --backtitle "INSERT NUMBER(s).." \
						 --msgbox "ERROR during reading memory from your phone... \
	                      Insert manually destination number." 8 60
			MEERROR=1
		else
			mv -f $SMSDIR/.MElist.temp $SMSDIR/.MElist.mem
		fi
	else
		MEERROR=1
	fi

	if [ $SMERROR -eq 1 ] && [ $MEERROR -eq 1 ]; then
		ERROR=1
	else
		ERROR=0
		cat $SMSDIR/.SMlist.sim > $SMSDIR/.PBKlist
		cat $SMSDIR/.MElist.mem >> $SMSDIR/.PBKlist
	fi
	if [ $ERROR -eq 0 ]; then
		# Parsing sim file...
		if [ ! -s $SMSDIR/.SMlist.chklst -o ! -s $SMSDIR/.SMlist.choice \
					-o $readsim -eq 1 -o $readme -eq 1 ] ; then
			> $SMSDIR/.SMlist.menu
			> $SMSDIR/.SMlist.chklst
			> $SMSDIR/.SMlist.choice
			totrows=`cat $SMSDIR/.PBKlist | wc -l`
			rownow=0
			(while read riga
			do
				rownow=`expr $rownow + 1`
				perc=`expr $rownow \* 100 / $totrows`
				pos=`echo $riga | cut -f4 -d";"`
				name=`echo $riga | cut -f1 -d";"`
				num=`echo $riga | cut -f2 -d";"`
				if [ -n "$pos" -a -n "$num" ] ; then
					echo -e "$pos \"$name - $num\"" >> $SMSDIR/.SMlist.menu
					echo -e "$pos \"$name - $num\" off" >> $SMSDIR/.SMlist.chklst
					echo "$pos;$num" >> $SMSDIR/.SMlist.choice
				fi
				echo $perc
			done < $SMSDIR/.PBKlist) | dialog \
				--gauge "Parsing phonebook file..." 12 70 0
		fi

		chkok=0
		option=0
		while [ $chkok -eq 0 ]
		do
			eval dialog --backtitle \"SENDSMS CKECKLIST\" \
									--checklist \"Check your MEMORY number\(s\).\
                              \\nPress ESC key \for options..... \" \
									16 60 9 \
									`cat $SMSDIR/.SMlist.chklst` 2> $TMP/rspTEMP02
			option=$?
			if [ $option -eq 255 ] ; then
				dialog --backtitle "SENDSMS CKECKLIST" --menu \
						"Options sub-menus for Phonebook choice list:" \
						10 50 4 \
						"1" "Sort by Memory Pos" \
						"2" "Sort by Names" \
						"9" "Quit $PROGNAME" 2> $TMP/rspTEMP04
				if [ $? -eq 0 ]; then
					sorttype=`cat $TMP/rspTEMP04`
					case $sorttype in
						1) sort -n $SMSDIR/.SMlist.chklst > $TMP/.SMlist.tmp
							 mv -f $TMP/.SMlist.tmp $SMSDIR/.SMlist.chklst
							 ;;
						2) sort +1 $SMSDIR/.SMlist.chklst > $TMP/.SMlist.tmp
							 mv -f $TMP/.SMlist.tmp $SMSDIR/.SMlist.chklst
							 ;;
						9) sure_to_quit
							 ;;
					esac
				fi
			else
				chkok=1
			fi
		done

		if [ $? -eq 0 ] ; then
			for val in `cat $TMP/rspTEMP02`
			do
				tok1=`eval echo $val`
				tok2=`grep "^$tok1;" $SMSDIR/.SMlist.choice`
				tok3=`echo $tok2 | cut -f2 -d";"`
				if [ -z "$NUMBERS" ] ; then
					NUMBERS="$tok3"
				else
					NUMBERS="$NUMBERS $tok3"
				fi
			done
		fi
	fi
}

###########################################################################
###########################################################################
#                               MAIN PROCEDURE                            #
###########################################################################
###########################################################################

parse_stdin $*

# This is the 'help' test...
# if [ "$1" = "--help" -o "$1" = "/h" ] ; then
# 	help
# fi

if ! type -all "dialog" >/dev/null 2>&1 ; then
echo
echo "${PROGNAME}: error:"
echo "Can't find 'dialog', i can't run without 'dialog' on your system."
echo "You can get a compiled elf version of 'dialog' from here."
echo "http://www.tux.org/pub/people/kent-robotti/index.html"
echo "ftp://ftp.tux.org/pub/people/kent-robotti 'dialog-0.9a-15.elf.tar.gz'"
echo
exit 1
fi

if [ $SW_SKIPGNOKITST = no ] ; then
	if ! type -all "$GNOKII" >/dev/null 2>&1 ; then
	echo
	echo "${PROGNAME}: error:"
	echo "Can't find 'gnokii'. This script needs 'gnokii' in order to work."
	echo "You can get a version of 'gnokii' from following links:"
	echo "GNOKII: http://www.gnokii.org/"
	echo
	echo "Source code and pre-compiled binaries for gnokii are available from "
	echo "a number of sites"
	echo
	echo "www.gnokii.org located in California, USA"
	echo "ftp.pl.gnokii.org located in Warsaw, Poland"
	echo
	exit 1
	fi
fi

if [ ! -d ~/tmp ]; then
mkdir ~/tmp
chmod 755 ~/tmp
fi

if [ ! -d $SMSDIR ]; then
mkdir -p $SMSDIR
chmod 755 $SMSDIR
fi

if [ -d $TMP ]; then
	rm -rf $TMP
fi
mkdir -p $TMP
chmod 700 $TMP


echo "$BACKTITLE" > $TMP/txtTEMP01
echo >> $TMP/txtTEMP01
echo "Written by Gabriele Zappi <gzappi@inwind.it> " >> $TMP/txtTEMP01
echo >> $TMP/txtTEMP01
echo "This script is a front-end to type SMS messages directly" >> $TMP/txtTEMP01
echo "from your computer and send them using gnokii through" >> $TMP/txtTEMP01
echo "your cellular phone connected to your computer." >> $TMP/txtTEMP01
echo >> $TMP/txtTEMP01
echo "Press [Enter] to continue with SENDSMS." >> $TMP/txtTEMP01

dialog --backtitle "$BACKTITLE" --textbox "$TMP/txtTEMP01" 14 70 
TURN=0

while true
do
	echo "Please, enter in the box below, your SMS message." > $TMP/txtTEMP$$ 
	echo "Remember that it cannot be longer than 160 chars." >> $TMP/txtTEMP$$ 
	echo " " >> $TMP/txtTEMP$$ 
	echo "Press [ESC] or [CANCEL] to quit the program. " >> $TMP/txtTEMP$$ 

	len=999
	if [ $TURN -eq 0 ]; then
		if [ "$SW_PRESETSMS" = "yes" ]; then
			echo "$PRESETSMS" > $TMP/rspTEMP01
		else
			> $TMP/rspTEMP01
		fi
	fi
	while test "$len" -le 0 -o "$len" -gt 160
	do
		dialog --backtitle "INSERT SMS ....." \
					 --inputbox  "`cat $TMP/txtTEMP$$`" 10 70 "`cat $TMP/rspTEMP01`" \
					 																						2> $TMP/rspTEMP01
	  if [ $? -ne 0 ] ; then
			sure_to_quit
		fi
		len=`cat $TMP/rspTEMP01 | wc -c `

		if [ $len -le 0 -o $len -gt 160 ] ; then
			echo "Invalid SMS: It must be < 160 chars and > 0 long.." > $TMP/txtTEMP02
			dialog --textbox "$TMP/txtTEMP02" 6 70 
		fi
	done

	NUMBERS=""
	okcycle=0
	while [ "$NUMBERS" = "" -o "$okcycle" -eq 0 ]
	do
		dialog --backtitle "INSERT NUMBER(s).." \
					 --yesno "Would you like to pick up number(s)\
                    from your phone memory?" 8 60
														

		if [ $? -eq 0 ] ; then # Yes, gimme num from phonebook.
			SMS_choicefrommem
		fi

		# Manual telephone number completion or insertion.
		echo "Please, insert/modify in the box below, the NUMBER(S)" > $TMP/txtTEMP$$ 
		echo "where you want to send the message to. " >> $TMP/txtTEMP$$ 
		echo "(Multiple numbers must be separated by a space.)  " >> $TMP/txtTEMP$$ 
		echo "Press [ESC] or [CANCEL] to quit the program. " >> $TMP/txtTEMP$$ 
		echo " " >> $TMP/txtTEMP$$ 
		echo "OUTGOING MESSAGE: " >> $TMP/txtTEMP$$ 
		echo -n "  "
		cat $TMP/rspTEMP01 | cut -c1-60 >> $TMP/txtTEMP$$
		cat $TMP/rspTEMP01 | cut -c61-120 >> $TMP/txtTEMP$$
		cat $TMP/rspTEMP01 | cut -c121-160 >> $TMP/txtTEMP$$
		
		okcycle=1
		dialog --backtitle "INSERT NUMBER(s).." \
					 --inputbox  "`cat $TMP/txtTEMP$$`" \
					 16 70 "$NUMBERS"  2> $TMP/rspTEMP03
	
	  if [ $? -ne 0 ] ; then
			sure_to_quit
			okcycle=0
		else
			NUMBERS=`cat $TMP/rspTEMP03`
			if [ "$NUMBERS" = "" ] ; then
				dialog --backtitle "INSERT NUMBER(s).." \
							 --infobox "Number cannot be empty.\n     Try again.." 4 28 
				sleep 2
				okcycle=0
			fi
		fi
	done

	# Last confirmation before sending messages....

	okcycle=0
	while [ $okcycle -eq 0 ]
	do
		echo "Ok. If you confirm the operation, then the SMS" > $TMP/txtTEMP$$ 
		echo "is going to be sent to the selected number(s)." >> $TMP/txtTEMP$$ 
		echo >> $TMP/txtTEMP$$ 
		echo "Press [ESC] to quit the program. " >> $TMP/txtTEMP$$ 
		echo "Press [CANCEL] to return to SMS input. "  >> $TMP/txtTEMP$$ 
		dialog --backtitle "$BACKTITLE" \
					 --yesno "`cat $TMP/txtTEMP$$`" 9 60
		case $? in
			0)
				okcycle=1;;
			1)
				TURN=`expr $TURN + 1`
				continue 2;;
			255)
				sure_to_quit ;;
		esac                                                                            
	done
	TURN=`expr $TURN + 1`

	for num in $NUMBERS
	do
		# echo "Sending sms to number $num ... "
		dialog --backtitle "$BACKTITLE" --infobox "Sending sms to number $num ...\n         Please wait" 4 45
		if [ "$SW_SIMUL" = "yes" ] ; then
			sleep 2
		else
			$GNOKII --sendsms $num < $TMP/rspTEMP01 > /dev/null 2>&1
		fi
		if [ $? -eq 0 ] ; then
			dialog --backtitle "$BACKTITLE" \
			--infobox "Message correctly sent to number $num !" 3 55 
		else
			dialog --backtitle "$BACKTITLE" \
			--infobox "Sent Failed to num $num! Sorry!" 3 55 
		fi
		sleep 2
	done

done


acex 0
# zap - fin qui
