#! /bin/sh
#
# DipEye	This shell script attempts to keep dip online.
#
# Version:	@(#)/usr/sbin/dipeye	0.40	09/04/94
#
# Author:	Adam Dace, <glide@mcs.net>

# Default files
DIP="/sbin/dip"
DIP_LOG="/var/adm/dipeye.log"

# The wonderful world of flags
typeset -i ONLINE

start_dip()
{
  # First off, if there are any copies of dip or ping currently running,
  # kill them.

  PID=`ps ax | grep "/sbin dip /home/thekind/bin/mcs.dip" | grep -v grep | cut -c -5`
  if [ "X${PID}" != "X" ]
  then
    kill ${PID}
    sleep 30s
  fi

  PID=`ps ax | grep "/bin/ping -i 180 ChiGate-1.mcs.com" | grep -v grep | cut -c -5`
  if [ "X${PID}" != "X" ]
  then
    kill ${PID}
  fi

  # Now boot dip.
  $DIP /home/thekind/bin/mcs.dip > /dev/null &

  # Wait for dip to try connecting.
  sleep 1m

  # Did dip succeed?
  PID=`ps ax | grep "/sbin dip /home/thekind/bin/mcs.dip" | grep -v grep | cut -c -5`
  if [ "X${PID}" != "X" ]
  then
    ONLINE=1
    echo -n "Successful DIP Connection:		" >> $DIP_LOG
    date >> $DIP_LOG

    # Start up a ping to my SLIP server, clear smail queue.
    /bin/ping -i 180 ChiGate-1.mcs.com > /dev/null &
    sleep 10m
    /usr/sbin/netdate kitten.mcs.com > /dev/null &
  else
    ONLINE=0
    echo -n "UnSuccessful DIP Connection:	" >> $DIP_LOG
    date >> $DIP_LOG

    # Hunt down my ping process and zaps it.
    PID=`ps ax | grep "/bin/ping -i 180 ChiGate-1.mcs.com" | grep -v grep | cut -c -5`
    if [ "X${PID}" != "X" ]
    then
      kill ${PID}
    fi
  fi

}

# Keep an eye on dip, testing every 5 minutes to make sure it's up
watch()
{
  while [ $ONLINE -eq 1 ]
  do
    PID=`ps ax | grep "/sbin dip /home/thekind/bin/mcs.dip" | grep -v grep | cut -c -5`
    if [ "X${PID}" = "X" ]
    then 
      ONLINE=0
      echo -n "DIP Connection Faliure:			" >> $DIP_LOG
      date >> $DIP_LOG
    else
      sleep 5m
    fi
  done
}

#---------------------------------
#main
#---------------------------------

# Check to see if dip exists.  If not, exit.
if [ -f $DIP ]
then start_dip
else
  echo "Can't find Dip!  Exiting..."
  exit 1
fi

# If dip doesn't connect the first time, wait 5 minutes and retry.
if [ $ONLINE -eq 0 ]
then
  sleep 5m
  start_dip
fi

# Go into infinite loop to maintain dip, waiting 1, and then 30 minutes
# between failures.
while true
do
  watch
  sleep 1m
  start_dip

  if [ $ONLINE -eq 0 ]
  then
    sleep 30m
    start_dip
  fi
done
