#!/bin/sh 
#
# SLIP-CHECK "port" "speed" "phone number"    
#               "ping-host" "username" "password"
#
# (eg. 6 args)

# Pings 'ping-host', if it gets no response, the SLATTACH is killed, 
# if running, and KERMIT is used to dial and connect, then SLATTACH
# is launched again. Presumably run from CRON, though it works manually.
# If the SLIP link is intact nothing happens.

PATH=/bin:/sbin:/usr/bin

PORT=$1
SPEED=$2
PHONE=$3
HOST=$4
USERNAME=$5
PASSWORD=$6

# What we use for a temp. and lock file:
TEMP=/tmp/slip-check.lock

# A hard lock-out flag file. This script silently stops if it
# encounters this file.
STOP=/tmp/slip-stop.lock

#
# Check for the stop flag; we use this to manually intervene.

if /bin/test -f $STOP ; then
	exit
fi

#
# If slip-check is already running (ie. still running from a previous
# invokation; possible on modem connect errors, etc) exit immediately.
# Of course if this file doesn't get killed properly then the whole
# thing comes to a grinding halt. We create the lock/temp file
# immediately, though cron won't invoke another copy for at least
# a minute. (Humans are less predictable.)

if /bin/test -f $TEMP ; then
	exit
fi
date > $TEMP 

# PING my router. It gets pinged N times; if it returns any one (or
# or more) packets then it's fine, eg the check for "0 received".

if /sbin/ping -c 1 ${HOST} | grep -s '0 packets received' ; then
  if /sbin/ping -c 1 ${HOST} | grep -s '0 packets received' ; then
    /bin/sleep 2
   if /sbin/ping -c 1 ${HOST} | grep -s '0 packets received' ; then
#      /bin/sleep 4
#      if /sbin/ping -c 1 -l 1 ${HOST} | grep -s '0 packets received' ; then

	/bin/date
	echo "The damned SLIP link dropped dead."

# This horrid thing sets var 'pid' to the PID of the running SLATTACH,
# if any. (386BSD tty drivers don't know anything about Carrier Detect!
# You have to assasinate them!)

	pid=`ps ax | grep slattach | grep -v grep | awk '{print $1;}'`
	if [ X${pid} != "X" ] ; then
		echo 'killing slattach, PID=' ${pid}
		kill -9 ${pid}
	fi

# KERMIT dial the damned thing, login, etc. STTY to 8 bits (redundant?
# apparently not) and NOHUP slattach. Requires CSH.

	/usr/local/bin/kermit /usr/local/etc/slip/kermit.dial = $PORT $SPEED $PHONE $USERNAME $PASSWORD
	stty -f ${PORT} -clocal cs8
	echo Restarting SLATTACH.
	/usr/bin/nohup /sbin/slattach ${PORT} ${SPEED} > /dev/null
	/sbin/ifconfig sl0 up
#      fi
    fi
  fi
fi

# Be clean and neat.
rm -f $TEMP
