#!/bin/bash

# a nice pppd utility script

# Last update:
# vr mei 24 13:42:11 CEST 2002

# Use with providers in the /etc/ppp/peers/ directory.
# The option lists in /etc/ppp/peers must use the
# updetach and linkname options. The linkname must be the
# same as the name of the option list itself.

# Requires: pppd, ps, sed, awk. Look in the email() function
# to customize email send/receive commands.


# Set default provider to call if none is given on the commandline:
default_provider=xs4all

# make provider name safe
provider=$(echo ${1:-$default_provider}|sed "s,[/ ],,g")
run_file="/var/run/ppp-$provider.pid"

unset PID
test -f $run_file && PID=$(sed -n 1p $run_file)

email()
{
	echo "sending mail..."
	/usr/sbin/masqmail -qo xs4all
	/usr/sbin/masqmail -qo oswf
	echo "fetching mail..."
	/usr/sbin/masqmail -g
}

on()
{
	if [ "$PID" ] ; then
	  error "ppp: interface for $provider already exists"
	  exit 1
	fi
	echo "trying to connect to $provider..."
	/usr/sbin/pppd call $provider
	if [ -f $run_file ] ; then
	  echo "connected!"
	else
	  error "ppp: connection to $provider failed"
	  exit 1
	fi
}

off()
{
	if [ "$PID" ] ; then
	  kill -INT $PID
	else
	  PID=$(ps ax|awk '/pppd call '$provider'$/ {print $1}')
	  if [ "$PID" ] ; then
	    kill -INT $PID
	  else
	    error "ppp: connection to $provider already closed"
	    exit 1
	  fi
	fi
	echo "connection to $provider closed."
}

error()
{
	test "$DISPLAY" && xmessage -nearmouse "$1"
	echo "$1" >&2
}

usage()
{
	echo
	echo "ppp -- a simple ppp utility script © 2002 by Wilbert Berendsen,"
	echo "       available under the GNU GPL.  NO WARRANTY!"
	echo
	echo "Usage:"
	echo "        ppp-on  [provider]"
	echo "        ppp-off  [provider]"
	echo "        ppp-email  [provider]"
	echo "        ppp-fastmail  [provider]"
	echo
	echo "ppp-on and ppp-off bring a named (default: $default_provider) PPP"
	echo "connection up, while ppp-email is a customisable script to send"
	echo "and fetch email, and ppp-fastmail does all in once: e.g. bring up"
	echo "PPP, send and fetch email, and terminate the connection."
	echo
	echo "See also:"
	echo "        /etc/ppp/peers/"
	echo "        pppd(8)"
	echo
	exit
}	

case "$0" in
	*ppp-on)	on ;;
	*ppp-off)	off ;;
	*ppp-email)	email ;;
	*ppp-fastmail)
		if [ "$PID" ] ; then
		  echo "ppp: warning: connection to $provider already exists"
		  email
		  echo "ppp: warning: connection to $provider NOT closed"
		else
		  on && sleep 10 && email
		  off
		fi
		;;
	*)	usage ;;
esac
