#! /bin/sh
. /usr/local/news/lib/innshellvars

##  $Revision: 4115 $
##  SH script to send NNTP news out.

PROGNAME=`basename $0`
LOG=${MOST_LOGS}/${PROGNAME}.log

##  Go to where the action is, start logging
cd $BATCH
umask 002
DEBUG=""
if [ "X$1" = X-d ] ; then
    DEBUG="-d"
    shift
else
    test ! -f ${LOG} && touch ${LOG}
    chmod 0660 ${LOG}
    exec >>${LOG} 2>&1
fi

echo "${PROGNAME}: [$$] begin `date`"

##  List of sitename:hostname pairs to send to
if [ -n "$1" ] ; then
    LIST="$*"
else
    echo "${PROGNAME}: [$$] no sites specified" >&2
    exit 1
fi

##  Do the work...
for SITE in ${LIST}; do
    case $SITE in
    *:*)
	HOST=`expr $SITE : '.*:\(.*\)'`
	SITE=`expr $SITE : '\(.*\):.*'`
	;;
    *)
	HOST=$SITE
	;;
    esac
    case $HOST in
    *@*)
        PORT=`expr $HOST : '\(.*\)@.*'` 
        HOST=`expr $HOST : '.*@\(.*\)'`
        ;;
    *)  
        PORT=119
        ;;
    esac
    BATCHFILE=${SITE}.nntp
    LOCK=${LOCKS}/LOCK.${SITE}
    trap 'rm -f ${LOCK} ; exit 1' 1 2 3 15
    shlock -p $$ -f ${LOCK} || {
	echo "${PROGNAME}: [$$] ${SITE} locked by `cat ${LOCK}`"
	continue
    }

    ##  See if any data is ready for host.
    if [ -f ${SITE}.work ] ; then
	cat ${SITE}.work >>${BATCHFILE}
	rm -f ${SITE}.work
    fi
    if [ ! -f ${SITE} -o ! -s ${SITE} ] ; then
	if [ ! -f ${BATCHFILE} -o ! -s ${BATCHFILE} ] ; then
	    rm -f ${LOCK}
	    continue
	fi
    fi
    mv ${SITE} ${SITE}.work
    ctlinnd -s -t30 flush ${SITE} || continue
    cat ${SITE}.work >>${BATCHFILE}
    rm -f ${SITE}.work
    if [ ! -s ${BATCHFILE} ] ; then
	echo "${PROGNAME}: [$$] no articles for ${SITE}"
	rm -f ${BATCHFILE}
	continue
    fi

    echo "${PROGNAME}: [$$] begin ${SITE}"
    time innxmit ${DEBUG} -P ${PORT} ${HOST} ${BATCH}/${BATCHFILE}
    echo "${PROGNAME}: [$$] end ${SITE}"
    rm -f ${LOCK}
done

echo "${PROGNAME}: [$$] end   `date`"
