#!/bin/sh
#
# links - start/check nntplink processes
#
# Written by: David Alden
# Date:       May 20th, 1991
#
PATH=/usr/lib/newsbin/local:$PATH; export PATH
trap "rm -f /tmp/links*; exit 0" 0 1 2 3 9 15

#
# Where is the list which contains the sites that we should startup nntplink
sitelist=/usr/lib/news/links-list

#
# Comment out this line if you don't want nntplink to automatically place
# itself in the background
autobackground=1

#
# Where are the batchfiles?
batchdir=/usr/spool/news/out.going

#
# What goes on the end of "${batchdir}/${site}" to get the link datafile?
# (ie: should we use "${batchdir}/${site}/togo.link" or should we use
# "${batchdir}/${site}.link"?)
# rest=/togo.link
rest=.link

#
# command to display all of the processes currently running
# ps_command="ps -e"			# Sys V
ps_command="ps -ax"			# BSD

#
# column in which the pid is in from the previous command
#pid_column=1				# Sys V
pid_column=1				# BSD

#
datafile=/tmp/links.$$
prog=`basename $0`
start=
sig=

case $1 in
-s)
    sig=$2
    ;;

start)
    start="true"
    ;;
check)
    ;;					# This is the default
*)
    echo "usage: $prog [start] [check] [-s signal]"
    exit
    ;;
esac

if [ -n "$start" ]; then

    echo -n "Starting links for:"

    while read pri site options
    do

	if [ "$pri" = "#" ]; then
	    continue
	fi

	nice -$pri nntplink ${autobackground:+-A} $options $site
	echo -n " $site"

    done < $sitelist

    echo "."
    sleep 5
fi

$ps_command | grep nntplink | grep -v grep > $datafile

while read pri site options
do

    if [ "$pri" = "#" ]; then
	continue
    fi

    tried_already=false

    while true
    do

	if [ -f $batchdir/$site$rest ]; then

	    pid=`head -1 $batchdir/$site$rest`

	    if [ "$pid" != "-999" ]; then
		awk_script="' \$$pid_column == $pid { print \"match\" } '"
		match=`eval awk $awk_script $datafile`

		if [ "$match" = "match" ]; then
		    if [ -n "$sig" ]; then
			kill -$sig $pid
		    fi
		    break
		else
		    echo "$prog: site $site has a bad pid in its datafile"
		    echo "$prog: human intervention is necessay"
		    break
		fi
	    fi
	fi

	if [ -n "$sig" ]; then
	    break
	fi

	if [ "$tried_already" != "true" ]; then
	    echo "$prog: site $site isn't running - trying to restart it"
	    nice -$pri nntplink ${autobackground:+-A} $options $site
	    tried_already=true
	    sleep 5
	    $ps_command | grep nntplink | grep -v grep > $datafile
	else
	    echo "$prog: site $site still not running - skipping"
	    break
	fi
    done

done < $sitelist
