#! /bin/bash
# $Id: gxdialup,v 1.8 2004/03/14 12:32:24 trm Exp trm $

## 
## Usage: @PROG@ [PROVIDER_LIST]
## 
## A simple ISP connection manager for a Debian machine with one or
## more dial-up accounts. (This could be useful as a window manager
## menu item or a GNOME launcher, say.)
## 
## PROVIDER_LIST is a comma-separated list of provider names and
## screen names. For example, if /etc/ppp/peers/ contains the files
## 'provider', 'clear' and 'telecom', you might invoke @PROG@ with:
## 
##     @PROG@ "IHUG=provider,ClearNET=clear,XTRA=telecom"
## 
# 2003-09-25 Tim Musson <trmusson@ihug.co.nz>


PROG=$(basename $0)
XMESSAGE=gxmessage

PROVIDER_LIST="default provider=provider"
TIMEOUT=40
MESSAGE_FONT="sans 14"
MESSAGE_FG="#333333"
MESSAGE_BG="#b7b5b8"
GEOMETRY="400x90"
POSITION="-center"
TIMESTAMP="$HOME/.gxdialup.tmp"


gxPon ()
{
  # Dial a named ISP
  /usr/bin/pon $1
}


gxPoff ()
{
  # Disconnect
  /usr/bin/poff >/dev/null
}


alreadyConnected ()
{
  # Return 0 if currently connected, otherwise 1
  [ -e "/var/run/ppp0.pid" ]
}


if [ "$1" = "-h" -o "$1" = "--help" ]; then
  sed -n '/^##/s/^## //p' $0 | sed -e "s/@PROG@/${PROG}/g"
  exit 0
elif [ "$#" -eq 1 ]; then
  PROVIDER_LIST="$1"
elif [ "$#" -ne 0 ]; then
  echo "Try '$PROG -h'" >&2
  exit 64
fi


if alreadyConnected; then
  if [ -f "$TIMESTAMP" ]; then
    message=$(< "$TIMESTAMP")
  else
    message="Connected."
  fi
  buttons="Disconnect now:101"
else
  message="Not connected."
  buttons=""
  num=0
  IFS_tmp=$IFS
  IFS=","
  for provider in $PROVIDER_LIST; do
    [ -n "$buttons" ] && buttons="$buttons,"
    showname[$num]="${provider%%=*}"
    realname[$num]="${provider##*=}"
    buttons="${buttons}Dial ${showname[$num]}:$(( 102 + num ))"
    (( num++ ))
  done
  IFS=$IFS_tmp
fi
buttons="$buttons,Okay:100"

$XMESSAGE $POSITION                       \
          -geometry "$GEOMETRY"           \
          -title "ISP Connection Status"  \
          -fn "$MESSAGE_FONT"             \
          -fg "$MESSAGE_FG"               \
          -bg "$MESSAGE_BG"               \
          -buttons "$buttons"             \
          -default Okay                   \
          "$message"

response=$?

if [ "$response" -eq 101 ]; then
  gxPoff
elif [ "$response" -ge 102 ]; then
  num=$(( response - 102 ))
  gxPon ${realname[$num]} || exit 1
  echo "Connected to ${showname[num]} since $(date +%T)" > "$TIMESTAMP"
  if [ "$TIMEOUT" -gt 0 ]; then
    $XMESSAGE $POSITION                       \
              -geometry "$GEOMETRY"           \
              -title "ISP Connection Status"  \
              -fn "$MESSAGE_FONT"             \
              -fg "$MESSAGE_FG"               \
              -bg "$MESSAGE_BG"               \
              -timeout $TIMEOUT               \
              -buttons ""                     \
              "Dialing ${showname[$num]}, please wait..." &
  fi
fi

exit 0

