#! /usr/bin/perl
# use -*- perl -*-
    eval 'exec perl -S $0 ${1+"$@"}'
        if $running_under_some_shell;

##############################################################
#
# Script wrapper, mails output if there is any
#
# Mainly intended for running cfengine.
#
##############################################################

if ($< != 0)
   {
   die "cfwrap: Bad luck, only root can run this one!\n";
   }

$mail = 0;

$prefix = "/usr/local";
$ENV{CFINPUTS} = "$prefix/lib/cfengine/inputs";
$ENV{LD_LIBRARY_PATH} = "/usr/ucblib";
$sysadm = `$prefix/sbin/cfengine -a`;

$comm = join(" ",@ARGV);
@path = split(m;/;,$comm);
$suff = $path[$#path];

if ( -d "/var/run/cfengine" )
   { 
   $tmpfile = "/var/run/cfengine/cfwrap.$$";
   $oldtmpfile = "/var/run/cfengine/oldcfwrap";
   unlink "/etc/oldcfwrap";
   }
elsif ( -d "/etc/cfengine" )
   {
   $tmpfile = "/etc/cfengine/cfwrap.$$";
   $oldtmpfile = "/etc/cfengine/oldcfwrap";
   unlink "/etc/oldcfwrap";
   }
else
   {
   $tmpfile = "/etc/cfwrap.$$";
   $oldtmpfile = "/etc/oldcfwrap";
   }

open (H,"/bin/hostname |") || die "cfwrap: Can't get hostname";
$hostname = <H>;
chop $hostname;
close(H);

open (SH,"$comm 2>&1 | ") || die "cfwrap: Can't start shell\n";
open (OUT,">$tmpfile") || die "cfwrap: Can't open workfile\n";

($s,$m,$h,$md,$mn,$yr,$wd,$yday) = localtime(time);

print OUT "Subject: cfengine ($hostname) ($yday)\n\n";
print OUT "This message originates from host $hostname on $today\n";
print OUT "The full command issued was: $comm.\n\n";

for ($i = 0; $i < $wd; $i++)
   {
   print OUT "+";
   }

print OUT "\n";

while (<SH>)
   {
   if ( /\S/ )
      {
      print OUT "$_";
      $mail = 1;
      }
   }

close(OUT);
close(SH);


 #
 # Only mail if mail is different or new day
 #


($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size1) = stat $oldtmpfile;
($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size2) = stat $tmpfile;


if (($size1 != $size2))
   {
   if ($mail)
      {
      system ("/bin/cat $tmpfile | $prefix/share/cfengine/cfmail $sysadm");
      }
   }

rename ($tmpfile,$oldtmpfile);

















