#! /bin/bash

## 
## Usage: @PROG@ [PROVIDER_LIST]
## 
## A simple ISP connection manager for a Debian machine with one or more
## dial-up accounts handled by pppconfig, pon, and poff. (This script is
## especially useful as a window manager menu item or a GNOME launcher.)
## 
## 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,Clear_NET=clear,_XTRA=telecom'
## 
# 2003-09-25 Tim Musson <trmusson@ihug.co.nz>


PROG=$(basename $0)
XMESSAGE=${XMESSAGE:-$(which gxmessage)} || XMESSAGE=xmessage
TIMESTAMP="$HOME/.gxdialup.tmp"

PROVIDER_LIST="_default provider=provider"
TIMEOUT=40

MSG_TITLE="ISP Connection Status"
MSG_FONT="sans 14"
MSG_FG=black
MSG_BG=white
MSG_GEOM="400x90"
MSG_POS="-center"


[ "$XMESSAGE" = xmessage ] && MSG_FONT=


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,GTK_STOCK_CLOSE:100"

$XMESSAGE $MSG_POS                        \
          -geometry "$MSG_GEOM"           \
          -title "$MSG_TITLE"             \
          ${MSG_FONT:+-fn "$MSG_FONT"}    \
          -fg "$MSG_FG"                   \
          -bg "$MSG_BG"                   \
          -buttons "$buttons"             \
          -default GTK_STOCK_CLOSE        \
          "$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 $MSG_POS                        \
              -geometry "$MSG_GEOM"           \
              -title "$MSG_TITLE"             \
              ${MSG_FONT:+-fn "$MSG_FONT"}    \
              -fg "$MSG_FG"                   \
              -bg "$MSG_BG"                   \
              -timeout $TIMEOUT               \
              -buttons ""                     \
              "Dialing ${showname[$num]/_/}, please wait..." &
  fi
fi

exit 0

