#! /bin/sh
# fixscript will replace this line with code to load innshellvars

##  $Revision: 1.2 $
##  Write a log file entry, by either mailing it or writing it safely.
##  Usage:
##	writelog name text... <input
##  where
##	name	is 'mail' to mail it, or filename to append to.

MAXTRY=60

##  Parse arguments.
if [ $# -lt 2 ] ; then
    echo "usage: $0 'logfile|mail' message ..." 1>&2
    exit 1
fi
LOGFILE="$1"
shift
MESSAGE="$@"

##  Handle the easy cases.
case "X${LOGFILE}" in
X/dev/null)
    exit 0
    ;;
Xmail)
    sed -e 's/^~/~~/' | ${MAILCMD} -s "${MESSAGE}" ${NEWSMASTER}
    exit 0
    ;;
esac

##  We're sending to a file.
LOCK=${LOCKS}/LOCK.`basename ${LOGFILE}`

##  Remember our PID, in case while is a sub-shell.
PID=$$
TRY=0

export LOCK MAXTRY PID LOGFILE ARTICLE MESSAGE TRY
while [ ${TRY} -lt ${MAXTRY} ]; do
    shlock -p ${PID} -f ${LOCK} && break
    sleep 2
    TRY=`expr ${TRY} + 1`
done

##  If we got the lock, update the file; otherwise, give up.
if [ ${TRY} -lt ${MAXTRY} ]; then
    echo "${MESSAGE}" >>${LOGFILE}
    ${SED} -e 's/^/    /' >>${LOGFILE}
    echo "" >>${LOGFILE}
    rm -f ${LOCK}
else
    ##  This goes to errlog, usually.
    echo "$0: Cannot grab lock ${LOCK}, held by:" `cat ${LOCK}` 1>&2
fi
