#! /bin/bash

## 
## 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=${XMESSAGE:-gxmessage}
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=fixed


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

exit 0

