#!/bin/sh
##############################################################
#
# wrapper script, mails output if there is any (and if changed)
# Mainly intended for running cfengine; more or less based on
# cfwrap which is written in perl. Also this one has some 
# "enhancements" (see the README). 
#
# (us) 21-12-97 v1.1
# (us) 23-12-97 v1.2 ok-file permits execution (local)
#		     noconf prohibits execution (global)
#		     on all hosts (silent)
# (us) 24-12-97 v1.3 Fixed: mail problem if error in cfe-script (could 
#		            not find sysadmin)
#
# Solaris Version & SunOS
#
# Copyright (c) Uwe Sievers 1997/98    <uwe@dwelle.de>
# GPL rules, vers. 2 or newer. Use this program at your own risk!
##############################################################
#
#----------------------- adopt to your needs ----------------------
prefix=/usr
exec_prefix=${prefix}
FILECF="${CFINPUTS:-"@pkgdata@"}/cron.cf"
CFENGINE=${exec_prefix}/sbin/cfengine
TMPFILE=/tmp/cfwrap.$$
OLDFILE=/tmp/cfwrap.o
NOCONF=$prefix/etc/noconf
USER=`/usr/bin/whoami`
HOST=`/usr/bin/hostname`
MAILER=/usr/bin/mailx
#------------------no changes should be nessesary below (hopefully)
COMM="$CFENGINE -f $FILECF"
SYSV=
BSD=
OK=


#cfe Vars
OSREL=`uname -r`
OSVERS=`uname -s`
export OSREL OSVERS

if [ "$USER" != "root" ] ; then
	echo "Bad luck, only root can run this one!"
	$MAILER -s "$USER tried to run cfcron on $HOST" root </dev/null
	exit 1
fi

# just a hook
if [ $OSVERS = SunOS -a $OSREL -lt 5 ] ; then
#    echo BSD
    :
else
#    echo SYSV
    :
fi

if [ -f $NOCONF ] ; then		# exit silently
	exit 1
fi

if [ -f .ok ] ; then 
    OK=true
else
    COMM=/bin/true
    unset OK
#    exit 0
fi

# does not work in case of error in cfe script
#SYSADM=`$CFENGINE -a -S -w -f $FILECF 2>/dev/null` 

SYSADM=`egrep '^[^#].*sysadm.*=' $FILECF | cut -f2 -d\( | cut -f1 -d\)`

SUBJECT="cfengine on $HOST start at `date`" 

echo "This message originates from host $HOST on `date '+%d.%m.%y'`" \
						>> $TMPFILE
if [ -n "$OK" ] ; then
    echo "The full command issued was: $COMM"   >> $TMPFILE
else
    echo "d i s a b l e d"			>> $TMPFILE
fi

[ -n "$OK" ] && $COMM >>$TMPFILE 2>&1

# only send mail if anything changes
/usr/bin/diff $TMPFILE $OLDFILE >/dev/null ||
	$MAILER -s "$SUBJECT" $SYSADM < $TMPFILE

rm $OLDFILE
mv $TMPFILE $OLDFILE
chmod 600 $OLDFILE
exit 0
