#!/bin/sh
#
# This script was written entirely to get around bugs in the Solaris 2.X
# serial I/O system.  After a port is used for dialout, this script is
# used to disable and reenable the port to put it in a working state
# for sure.  It also checks to make sure that the port monitor is running
# and restarts it, if necessary.  This whole script should not be
# necessary.
#
. /etc/dp.conf
LOGFILE=$DPLOG_DIR/ttymon.log
LOCKFILE=/tmp/reset_ttymon.lock
TMPFILE=/tmp/reset_ttymon.$$
trap "rm -f $TMPFILE" 0 1 2 3 15
PMADM=/usr/sbin/pmadm
SACADM=/usr/sbin/sacadm
dev=$3
if [ -z "$dev" ] ; then
    exit 0
fi
service=`expr $dev : '.*/\(.*\)'`
type=`expr $dev : '.*/\(.*\)/.*'`
case $service in
 [0-9]*)
    pm=stsmon
    case $type in 
     term)
	;;
     cua)
	if [ $service -ge 11 ] ; then
	    #
	    # Assume one or more ST-1008
	    #
	    service=`expr $service - 9`
	elif [ $service -ge 5 ] ; then
	    #
	    # Assume single ST-1002
	    #
	    service=`expr $service - 3`
	fi
    esac
    ;;
 [ab])
    pm=zsmon
    service=tty$service
    ;;
 *)
    exit 0
    ;;
esac
notexist=`(pmadm -l -p $pm -s $service 2>&1) | grep "does not exist" | wc -l`
if [ $notexist -eq 1 ] ; then
    exit 0
fi
sleep 4
if [ -f $LOCKFILE ] ; then
    echo `date` "	" "$pm	$service" "busy" >> $LOGFILE
    exit 0
fi
pid1=$$
echo $pid1 > $LOCKFILE
sleep 4
pid2=`cat $LOCKFILE`
if [ "$pid1" != "$pid2" ] ; then
    echo `date` "	" "$pm	$service" "collision" >> $LOGFILE
    exit 0
fi
trap "rm -f $TMPFILE $LOCKFILE" 0 1 2 3 15
($PMADM -d -p $pm -s $service ; sleep 2 ;$PMADM -e -p $pm -s $service) > $TMPFILE 2>&1
notrunning=`grep "is not running" $TMPFILE|wc -l"`
if [ $notrunning -gt 0 ] ; then
    echo "Restarting $pm" >> $TMPFILE
    $SACADM -s -p $pm >> $TMPFILE 2>&1
fi
(echo `date` "	" "$pm	$service" ; cat $TMPFILE) >> $LOGFILE
exit 0
