#! /bin/sh
##
##  Sendbatches for INN.
##
##  $Revision: 1.5 $
##  SH script to send general batches out.

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

# =()<BATCH=@<_PATH_BATCHDIR>@>()=
BATCH=/var/spool/news/out.going
# =()<LIB=@<_PATH_NEWSLIB>@>()=
LIB=/usr/local/news
# =()<LOCKS=@<_PATH_LOCKS>@>()=
LOCKS=/usr/local/news
## =()<TMPDIR=${TMPDIR-@<_PATH_TMP>@}>()=
TMPDIR=${TMPDIR-/tmp}
XPID=$$ ; export XPID

PNAME=`basename $0`
CTLFILE=${LIB}/${PNAME}.ctl

## Go to the right dir
cd ${BATCH}

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

if [ ! -z "$1" ] ; then
    LIST="$*"
else
    echo "${PNAME}: [$$] no site specified"
    exit 1
fi

##  Get the default entry -- Note [space-tab] and not several spaces
default="`egrep \"^/default/[ 	]\" $CTLFILE | sed 1q`"

##  Do the work...
for SITE in ${LIST}; do
    BATCHFILE=${SITE}.batch
    if [ -f ${SITE}.work ] ; then
        cat ${SITE}.work >>${BATCHFILE}
        rm ${SITE}.work
    fi
    mv ${SITE} ${SITE}.work
    ctlinnd -s -t30 flush ${SITE} || {
       echo "${PNAME}: [$$] Can't flush ${SITE}."
       continue
    }
    cat ${SITE}.work >>${BATCHFILE}
    rm -f ${SITE}.work
    if [ ! -s ${BATCHFILE} ] ; then
        echo "${PNAME}: [$$] no articles for ${SITE}"
        continue
    fi

    # Between the brackets: one space + one tabulation
    ctlline="`egrep \"^$SITE[ 	]\" $CTLFILE | sed 1q`"
    if test "$ctlline" = ""
    then
       if test "$default" = ""
       then
	  echo "${PNAME}: [$$] no /default/ entry in ctlfile. Skipping ${SITE}"
	  continue
       fi
       set $default
    else
       set $ctlline
    fi
    batchnum=$2
    batchsize=$3
    muncher=$4
    sender="$5 ${SITE}"
    shift; shift; shift; shift; shift
    sender="$sender $*"
    ##  Get the compression flags.
    echo "${PNAME}: [$$] begin ${SITE}"
    batcher -N$batchnum -b$batchsize \
        -p"$muncher | $sender" ${SITE} ${BATCHFILE}
    echo "${PNAME}: [$$] end ${SITE}"
done

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