#! /bin/sh -
##############################################################################
# spoolnotes
#    Script to spool notes batches locally for later remote pickup.
#    It is assumed that the remote system can fetch them from this
#    host's local filesystem later either by ftp, rcp, or rfa.  See
#    the fetchnotes script for use on the other end.
#
# Usage:  spoolnotes [-c] remotesysname [moresysnames ...]
#
# The optional -c flag indicates that the batches should be
# compressed (probably not worth the cpu time in any high-speed network).
#
# Original:  Tw Cook <tw@hpcea.HP.COM> 21 November 1986
##############################################################################

ECHO=__ECHO__
CHMOD=__CHMOD__
AWK=__AWK__
SPOOLDIR=__SPOOLOUTDIR__

if [ $# -lt 1 ]
then
    $ECHO Usage: spoolnotes [-c] [-a] remotesysname [moresysnames ...]
    $ECHO "\t-c  compress batches before spooling"
    $ECHO "\t-a  spool for anonymous ftp (i.e. spool under ~ftp)"
    exit 1
fi

COMPRESS=__CAT__

if [ "$1" = "-c" ]
then
    COMPRESS=__COMPRESS__
    shift
fi

if [ "$1" = "-a" ]
then
    # Spool for anonymous FTP
    ANONHOME=`$AWK -F: '$1 == "ftp" { print $6; exit; }' < /etc/passwd`
    if [ "$ANONHOME" = "" ]
    then
	$ECHO "$0: could not find home directory for anonymous ftp"
	exit 1
    fi
    SPOOLDIR=${ANONHOME}${SPOOLDIR}
    shift
fi

REMOTENAME=$1
shift
MORENAMES="$@"

if [ "$REMOTENAME" = "" ]
then
    $ECHO Usage: spoolnotes [-c] [-a] [-n] remotesysname [moresysnames ...]
    exit 1
fi

# Make sure we can get into the appropriate spool directory(s).

if [ ! -d $SPOOLDIR ]
then
    mkdir $SPOOLDIR
    if [ ! -d $SPOOLDIR ]
    then
	$ECHO $0": couldn't make a directory $SPOOLDIR"
	exit 1
    fi
fi

for name in $REMOTENAME $MORENAMES tmp
do
    if [ ! -d $SPOOLDIR/$name ]
    then
	mkdir $SPOOLDIR/$name
	if [ ! -d $SPOOLDIR/$name ]
	then
	    $ECHO $0": couldn't make a directory $SPOOLDIR/$name"
	    exit 1
	else
	    $CHMOD 777 $SPOOLDIR/$name
	fi
    fi
done

cd $SPOOLDIR/tmp

# Keep trying to make up a unique filename until we
# find one that isn't already here.   When we do, create
# it so other invocations of this script won't steal it
# from us.   There is probably a tiny window here when
# it is possible that two processes could grab the same
# file;  that isn't likely, but we don't have an easy
# workaround for that.

filename=`date '+%a.%T'`

while [ -r $filename ]
do
    filename=`date '+%a.%T'`
done

touch $filename
$CHMOD 666 $filename

$COMPRESS > $filename

for name in $REMOTENAME $MORENAMES
do
    if [ -r ../$name/$filename ]
    then
        nfilename=`date '+%a.%T'`
	while [ -r ../$name/$nfilename ]
	do
	    nfilename=`date '+%a.%T'`
	done
	ln $filename ../$name/$nfilename
    else
        ln $filename ../$name/$filename
    fi
done

rm -f $filename

exit 0
