#! /bin/sh
##  $Revision: 1.9 $
##  SH script to send UUCP batches out.

# =()<NEWSBIN=@<_PATH_NEWSBIN>@>()=
NEWSBIN=/usr/local/news/bin
PATH=${NEWSBIN}:${PATH}:/bin:/usr/bin ; export PATH
# =()<AWK=@<_PATH_AWK>@>()=
AWK=/usr/local/bin/gawk

# =()<BATCH=@<_PATH_BATCHDIR>@>()=
BATCH=/var/spool/news/out.going
# =()<NEWSLIB=@<_PATH_NEWSLIB>@>()=
NEWSLIB=/usr/local/news
# =()<LOCK=@<_PATH_LOCKS>@/LOCK.uucp>()=
LOCK=/usr/local/news/LOCK.uucp
## =()<TMPDIR=${TMPDIR-@<_PATH_TMP>@}>()=
TMPDIR=${TMPDIR-/tmp}
# =()<HAVE_UUSTAT=@<HAVE_UUSTAT>@>()=
HAVE_UUSTAT=DONT

PNAME=`basename $0`
MAXJOBS=200

##  Start logging.
exec >>${NEWSLIB}/${PNAME}.out 2>&1
echo "${PNAME}: [$$] begin `date`"
cd ${BATCH}

##  Anyone else there?
trap 'rm -f ${LOCK} ; exit 1' 1 2 3 15
shlock -p $$ -f ${LOCK} || {
    echo "${PNAME}: [$$] locked by [`cat ${LOCK}`]"
    exit 0
}

##  Who are we sending to?
if [ -n "$1" ] ; then
    LIST="$*"
else
    LIST=""
    case `date +%H` in
    01|04|07|21|23)
	LIST="kurz-ai aoa clsib21 leafusa metasoft"
	;;
    06|12|15|17|20)
	LIST="esca"
	;;
    esac
fi

case ${HAVE_UUSTAT} in
DONT)
    TEMP=${TMPDIR}/uuq$$
    uuq -h |tr -d : >${TEMP}
    ;;
esac

##  Do the work...
for SITE in ${LIST}; do

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

    ##  Get number of jobs for the current site.
    case ${HAVE_UUSTAT} in
    DONT)
	JOBS=`${AWK} \
	    'BEGIN{X=0}  {if ($1 == "'$SITE'") X=$2}  END{print X}' <${TEMP}`
	;;
    DO)
	JOBS=`uustat -s${SITE} | grep rnews | wc -l`
	;;
    *)
	JOBS=0
	;;
    esac
    if [ ${JOBS} -ge ${MAXJOBS} ] ; then
	echo "${PNAME}: [$$] ${JOBS} files already queued for ${SITE}"
	continue
    fi
    QUEUEJOBS=`expr ${MAXJOBS} - ${JOBS}`

    ##  Get the compression flags.
    echo "${PNAME}: [$$] begin ${SITE}"
    case "${SITE}" in
    esca)
	COMPRESS="compress -b12"
	;;
    *)
	COMPRESS="compress"
	;;
    esac

    time batcher -N ${QUEUEJOBS} \
	-p"(echo '#! cunbatch' ; exec ${COMPRESS} ) | uux - -r %s!rnews" \
	${SITE} ${BATCHFILE}

    echo "${PNAME}: [$$] end ${SITE}"
done

case ${HAVE_UUSTAT} in
DONT)
    rm -f ${TEMP}
    ;;
esac

##  Remove the lock file.
rm -f ${LOCK}

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