#/bin/bash

# PPP connection handling script
# Copyright 1997 Piero Orsoni (orsoni@programmers.net)
# Last modified 7/MAY/1997
#
# This program comes under the GNU General Public License.
# a copy of the GPL should be distributed along with this software,
# usually with the file name "COPYING".
# if there is no such GPL, write to the Free Software Foundation, Inc.,
# 675 Mass Ave, Cambridge, MA 02139, USA

# Configurable items (default to a "normal" linux system):

# The directory where the program will put its connection scripts
DIRECTORY=$HOME/.ppp

# The name of the log file which contains the chat and pppd messages
LOG=/var/log/messages

# The netmask of the ppp interface (usually no need to change)
NETMASK=255.255.255.0

# The local IP (0.0.0.0=get from remote host, default that will usually work)
LOCAL_IP=0.0.0.0

# The serial device to use
SERDEV=modem

# The speed of the serial device. See "man setserial" for details.
SPEED=38400

# Where to find the pppd daemon
PPPDPATH=/usr/sbin

# The command line used to run the pppd daemon
# You may want to add the "debug" flag or raise the "kdebug" level to look
# for errors.
PPPCOMMAND="$PPPDPATH/pppd lock $SERDEV crtscts /dev/$SERDEV $SPEED \
	asyncmap 20A0000 escape FF kdebug 0 $LOCAL_IP:$REMOTE_IP \
	noipdefault netmask $NETMASK defaultroute connect \
	$DIRECTORY/"

# The chat command line
# Here you can change timeouts, but changing other values may cause the
# program to fail.
CHAT="exec chat -v                                      \
        TIMEOUT         3                               \
        ABORT           '\nBUSY\r'                      \
        ABORT           '\nNO ANSWER\r'                 \
        ABORT           '\nRINGING\r\n\r\nRINGING\r'    \
        ''              \rAT                            \
        'OK-+++\c-OK'   ATH0                            \
        TIMEOUT         30                              \
        OK              ATDT\$TELEPHONE                 \
        CONNECT         ''                              \
        \$LOGPROM       \$ACCOUNT                       \
        \$PASSPROM      \$PASSWORD
"

# What to do while connecting?
# LOG	   = show logs
# DIALOG   = show dialogs about connection progress
# anything = do nothing
ACTION=DIALOG

# Use less to show logs? (YES=yes, anything=no)
# else uses dialog text viewer
USELESS=NO

# End of configurable part.


VERSION=0.1.2


esci() {

rm /tmp/rep25 2>/dev/null
exit

}


exist() {

if [ "`cd $DIRECTORY; echo *`" = "*" ]; then
	dialog --backtitle "PPP Connection Handling $VERSION" --title "Error" --msgbox \
	"No connection present. Please create some" 6 30
	false
fi

}


connect() {

if test -e /tmp/ppp-device; then
	if ! dialog --backtitle "PPP Connection Handling $VERSION" --title "Warning" --yesno \
	"You are already connected using network device `cat /tmp/ppp-device`. Do you wish to \
continue and disconnect from the old session?" 8 44; then
		return 1
	fi
fi

if exist; then

if test -e /var/lock/LCK..$SERDEV; then
	if ps -xa | grep $[10#`cat /var/lock/LCK..$SERDEV`] | grep pppd; then
		dialog --backtitle "PPP Connection Handling $VERSION" --title "Info" --infobox \
			"Killing old pppd daemon..." 3 38
		kill -INT `cat /var/lock/LCK..$SERDEV`
		sleep 2
	fi
	if test -e /var/lock/LCK..$SERDEV; then
		dialog --backtitle "PPP Connection Handling $VERSION" --title "Error" --msgbox \
		"The /dev/$SERDEV serial device is locked by a non-pppd \
process. If you think you have no process running on /dev/$SERDEV, try \
removing the lock file: \"rm /var/lock/LCK..$SERDEV\"." 9 50
		return 1
	fi
fi

IDS=""
for i in `cd $DIRECTORY; echo *`; do
	IDS="$IDS $i `grep DESC $DIRECTORY/$i | cut -d = -f 2-`"
done

SAVSIZE=`wc $LOG | awk {'print $1'}`

if dialog --backtitle "PPP Connection Handling $VERSION" --title "Connect menu" --menu \
	"Please choose your way through the internet:" 18 42 10 \
	$IDS 2>/tmp/rep25; then
	if ! $PPPCOMMAND`cat /tmp/rep25`; then
		dialog --backtitle "PPP Connection Handling $VERSION" \
		--title "Error" --msgbox "Error trying to run the pppd daemon." 5 40
		return 1
	fi
else return 1
fi

if [ "$ACTION" != "LOG" ] && [ "$ACTION" != "DIALOG" ]; then return 1
fi

if ! test -r $LOG; then
	dialog --backtitle "PPP Connection Handling $VERSION" --title "Error" --msgbox \
	"Something went wrong. Maybe you have no read acces to the \
log file or maybe its name, $LOG, is mispelled." 8 42
	return 1
fi

clear
TRIES=0
TIMEOUT=45

if [ "$ACTION" = "LOG" ]; then
	DOACTION="/dev/stdout"
	DODIALOG="true"
else
	DOACTION="/dev/null"
	DODIALOG="dialog"
fi

$DODIALOG --backtitle "PPP Connection Handling $VERSION" --title "Info" --infobox \
	"Checking modem..." 3 30

while [ 1 ]; do
	CURSIZE=`wc $LOG | awk {'print $1'}`
	if [ "$CURSIZE" != "$SAVSIZE" ]; then
		TRIES=0
		tail -n $[$SAVSIZE - $CURSIZE] $LOG | tee /tmp/ppp-log-1 > $DOACTION
	else
		TRIES=$[$TRIES + 1]
		>/tmp/ppp-log-1
	fi
	SAVSIZE=$CURSIZE
	if grep "Failed" /tmp/ppp-log-1 | grep chat >/dev/null; then
		$DODIALOG --backtitle "PPP Connection Handling $VERSION" --title "Error" --msgbox \
		"The connection was unsuccesfull." 5 40
		break
	fi
	CONLINE=`grep "Using interface" /tmp/ppp-log-1 | grep pppd`
	if [ "$CONLINE" != "" ]; then
		echo $CONLINE | awk {'print $8'} > /tmp/ppp-device
		chmod go-rwx /tmp/ppp-device
		$DODIALOG --backtitle "PPP Connection Handling $VERSION" --title "Connected!" --msgbox \
		"Connection estabilished! Using network device `cat /tmp/ppp-device`." 6 40
		break
	fi
	if grep "Exit." /tmp/ppp-log-1 | grep pppd >/dev/null; then
		$DODIALOG --backtitle "PPP Connection Handling $VERSION" --title "Error" --msgbox \
		"The pppd daemon exited prematurely." 5 40
		break
	fi
	if [ "$[$TRIES < $TIMEOUT + 3]" = "0" ]; then
		$DODIALOG --backtitle "PPP Connection Handling $VERSION" --title "Error" --msgbox \
		"Timed out waiting for connection." 5 40
		break
	fi
	if grep "OK -- got it" /tmp/ppp-log-1 >/dev/null; then
		$DODIALOG --backtitle "PPP Connection Handling $VERSION" --title "Info" --infobox \
			"Dialing..." 3 30
	fi
	if grep "CONNECT -- got it" /tmp/ppp-log-1 >/dev/null; then
		$DODIALOG --backtitle "PPP Connection Handling $VERSION" --title "Info" --infobox \
			"Doing authentication..." 3 30
	fi
	TIMENEW=`grep "timeout set to" /tmp/ppp-log-1 | tail -1 | awk {'print $9'}`
	if [ "$TIMENEW" != "" ]; then
		TIMEOUT=$TIMENEW
	fi
	sleep 1
done

rm /tmp/ppp-log-1

if [ "$ACTION" = "LOG" ]; then
	echo "Tap enter to go on."
	read
fi

fi

}


disconnect() {

if ! test -e /tmp/ppp-device; then
	dialog --backtitle "PPP Connection Handling $VERSION" --title "Error" --msgbox \
	"Not connected." 5 30
	return 1
fi
if ! kill -INT `cat /var/run/\`cat /tmp/ppp-device\`.pid`; then
	dialog --backtitle "PPP Connection Handling $VERSION" --title "Error" --msgbox \
	"Unable to kill the pppd daemon." 5 40
fi
rm /tmp/ppp-device

dialog --backtitle "PPP Connection Handling $VERSION" --title "Message" --msgbox \
"Disconnected." 5 30

}


create() {

if ! dialog --backtitle "PPP Connection Handling $VERSION" --title "Create new connection" --inputbox \
	"Enter connection file name. This will be used to identify the \
connection." 10 40 2>/tmp/rep25; then
	return 1
fi

NAME=`cat /tmp/rep25`
if [ "$NAME" = "" ]; then return 1
fi

if ! dialog --backtitle "PPP Connection Handling $VERSION" --title "Create new connection" --inputbox \
	"Enter connection description. Don't use spaces, quotes, \
parentheses, etc. This is just cosmethic stuff." 10 40 \
	2>/tmp/rep25; then
	return 1
fi

DESC=`cat /tmp/rep25`
if [ "$DESC" = "" ]; then DESC="<no_description>"
fi

if ! dialog --backtitle "PPP Connection Handling $VERSION" --title "Create new connection" --inputbox \
	"Enter telephone number of the remote modem." 9 40 2>/tmp/rep25; then
	return 1
fi

TELEPHONE=`cat /tmp/rep25`

if ! dialog --backtitle "PPP Connection Handling $VERSION" --title "Create new connection" --inputbox \
	"Enter account for authentication on the remote host." 9 40 2>/tmp/rep25; then
	return 1
fi

ACCOUNT=`cat /tmp/rep25`

if ! dialog --backtitle "PPP Connection Handling $VERSION" --title "Create new connection" --inputbox \
	"Enter the password of this account." 8 40 2>/tmp/rep25; then
	return 1
fi

PASSWORD=`cat /tmp/rep25`

if ! dialog --backtitle "PPP Connection Handling $VERSION" --title "Create new connection" --inputbox \
	"Enter the last letters of the login prompt of the remote host \
(e.g. ogin: for unix boxes or sername: for cisco routers)" 11 40 2>/tmp/rep25; then
	return 1
fi

LOGPROM=`cat /tmp/rep25`

if ! dialog --backtitle "PPP Connection Handling $VERSION" --title "Create new connection" --inputbox \
	"Enter the last letters of the password prompt (e.g. assword:)" \
	9 40 2>/tmp/rep25; then
	return 1
fi

PASSPROM=`cat /tmp/rep25`

if dialog --backtitle "PPP Connection Handling $VERSION" --title "Create new connection" --yesno \
	"Is there a command to launch on the remote host to start the ppp connection?" \
	7 40; then

	if ! dialog --backtitle "PPP Connection Handling $VERSION" --title "Create new connection" --inputbox \
		"Enter the prompt to wait for before launching the command \
(e.g. $ or > for unix, > for cisco routers)" 10 40 2>/tmp/rep25; then
		return 1
	fi

	REMPROM=`cat /tmp/rep25`

	if ! dialog --backtitle "PPP Connection Handling $VERSION" --title "Create new connection" --inputbox \
		"Enter the command to be launched (e.g. ppp)" \
		9 40 2>/tmp/rep25; then
		return 1
	fi

	REMCOM=`cat /tmp/rep25`
else
	REMCOM=""
fi

echo DESC=$DESC > $DIRECTORY/$NAME
chmod go-rwx $DIRECTORY/$NAME
echo TELEPHONE=\'$TELEPHONE\' >> $DIRECTORY/$NAME
echo ACCOUNT=\'$ACCOUNT\' >> $DIRECTORY/$NAME
echo PASSWORD=\'$PASSWORD\' >> $DIRECTORY/$NAME
echo LOGPROM=\'$LOGPROM\' >> $DIRECTORY/$NAME
echo PASSPROM=\'$PASSPROM\' >> $DIRECTORY/$NAME

if ! [ "$REMCOM" = "" ]; then
	echo REMPROM=\'$REMPROM\' >> $DIRECTORY/$NAME
	echo REMCOM=\'$REMCOM\' >> $DIRECTORY/$NAME
fi

echo >> $DIRECTORY/$NAME
echo -n $CHAT >> $DIRECTORY/$NAME

if ! [ "$REMCOM" = "" ]; then
	echo -n \ \$REMPROM \$REMCOM >> $DIRECTORY/$NAME
fi

echo >> $DIRECTORY/$NAME

chmod u+x $DIRECTORY/$NAME

}


edit () {

if exist; then

IDS=""
for i in `cd $DIRECTORY; echo *`; do
	IDS="$IDS $i `grep DESC $DIRECTORY/$i | cut -d = -f 2-`"
done

if dialog --backtitle "PPP Connection Handling $VERSION" --title "Edit menu" --menu \
	"Edit which?" 18 42 10 \
	$IDS 2>/tmp/rep25; then
	$EDITOR $DIRECTORY/`cat /tmp/rep25`
fi

fi
}


delete() {

if exist; then

IDS=""
for i in `cd $DIRECTORY; echo *`; do
	IDS="$IDS $i `grep DESC $DIRECTORY/$i | cut -d = -f 2-`"
done

if dialog --backtitle "PPP Connection Handling $VERSION" --title "Delete menu" --menu \
	"Delete which?" 18 42 10 \
	$IDS 2>/tmp/rep25; then
	rm $DIRECTORY/`cat /tmp/rep25`
fi

fi

}


logs() {

if ! test -r $LOG; then
	dialog --backtitle "PPP Connection Handling $VERSION" --title "Error" --msgbox \
	"Something went wrong. Maybe you have no read acces to the \
log file or maybe its name, $LOG, is mispelled." 8 42
	return 1
fi

dialog --backtitle "PPP Connection Handling $VERSION" --title "Working" --infobox \
	"Preparing logs for viewing..." 3 40
grep chat $LOG > /tmp/ppp-log-1
grep pppd $LOG > /tmp/ppp-log-2

if [ "$USELESS" = "YES" ]; then
	sort -m /tmp/ppp-log-[12] | less -M +G
else
	sort -m /tmp/ppp-log-[12] > /tmp/ppp-log-3
	dialog --backtitle "PPP Connection Handling $VERSION" \
	--title "Log viewer" --textbox /tmp/ppp-log-3 20 80
fi

rm /tmp/ppp-log-[123]

}


timeinfo() {

if ! test -e /tmp/ppp-device; then
	dialog --backtitle "PPP Connection Handling $VERSION" --title "Error" --msgbox \
	"Not connected." 5 30
	return 1
fi

if ! test -e /var/run/`cat /tmp/ppp-device`.pid; then
	dialog --backtitle "PPP Connection Handling $VERSION" --title "Error" --msgbox \
	"Can't get information about network device `cat /tmp/ppp-device`." 6 40
	return 1
fi

INITIAL=`ls -l /var/run/\`cat /tmp/ppp-device\`.pid | awk {'print $8'}`
NOW=`date | awk {'print $4'} | cut -d : -f 1-2`
INMIN=$[10#`echo $INITIAL | cut -d : -f 1-1` * 60 + 10#`echo $INITIAL | cut -d : -f 2-2`]
NOWMIN=$[10#`echo $NOW | cut -d : -f 1-1` * 60 + 10#`echo $NOW | cut -d : -f 2-2`]
TIME=$[$NOWMIN - $INMIN]

if [ "$[$TIME < 0]" = "1" ]; then
	TIME=$[1440 + $TIME]
fi

dialog --backtitle "PPP Connection Handling $VERSION" --title "Time info" --msgbox \
	"Now it's $NOW. You have been connected since $INITIAL, for $TIME minutes." 6 44

}


info() {

while dialog --backtitle "PPP Connection Handling $VERSION" --title "Info Menu" --menu \
	"What do you want to see?" 11 34 4 \
	T "Connection time" \
	L "Logs" \
	A "About the program" \
	Q "Quit" \
	2> /tmp/rep25

do case `cat /tmp/rep25` in
	T) timeinfo ;;
	L) logs ;;
	A) dialog --backtitle "PPP Connection Handling $VERSION" --title "About" --textbox $0 20 76 ;;
	Q) esci ;;
esac
done

}


manage() {

while dialog --backtitle "PPP Connection Handling $VERSION" --title "Connection management menu" --menu \
	"Modify how?" 11 38 4 \
	C "Create new connection" \
	E "Edit connection" \
	D "Delete connection" \
	Q "Quit" \
	2> /tmp/rep25

do case `cat /tmp/rep25` in
	C) create ;;
	E) edit ;;
	D) delete ;;
	Q) esci ;;
esac
done

}


mkdir $DIRECTORY 2>/dev/null

case $1 in
	-[h?])	echo "PPP connection handling script - (C) 1997 Piero Orsoni (orsoni@programmers.net)"
		echo "Version $VERSION"
		echo "This program comes under the GNU General Public License. see COPYING for details"
		echo
		echo "ppp with no command line options starts in interactive mode"
		echo "ppp -c <filename> connect using <filename> connection script"
		echo "ppp -d disconnect"
		echo "ppp -h or ppp -? shows this help screen"
		echo "man ppp for more"
		echo
		echo "WARNING: mixing interactive operation with command line invocations may cause"
		echo "errors."
		exit ;;
	-c)	if [ "$2" != "" ] && test -e $DIRECTORY/$2; then \
			if ! $PPPCOMMAND/$2; then
				echo "Error trying to run the pppd daemon."
			fi
		else	echo "Can't open $DIRECTORY/$2"
		fi
		exit ;;
	-d)	if ! kill -INT `cat /var/run/`cat /tmp/ppp-device`.pid`; then
			echo "Unable to kill the pppd daemon."
		fi
		exit ;;
	*)	if ! [ "$1" = "" ]; then
			echo "Wrong command line option. enter ppp -h for help"
			exit
		fi ;;
esac

while dialog --backtitle "PPP Connection Handling $VERSION" --title "Main menu" --menu \
	"What next?" 12 38 5 \
	C "Connect!" \
	D "Disconnect" \
	M "Connection management" \
	I "Information" \
	Q "Quit" \
	2> /tmp/rep25

do case `cat /tmp/rep25` in
	C) connect ;;
	D) disconnect ;;
	M) manage ;;
	I) info ;;
	Q) esci ;;
esac
done

esci
