#!/bin/sh

MASTCONF="/etc/lrp.conf"
[ -f $MASTCONF ] && . $MASTCONF

# defaults if not re-defined by configuration file
su_usr=root
cmd="echo No command defined! && exit 1"
mailto=$lrp_MAIL_ADMIN
subject="No subject defined!"
details=no
mailalways=no

# General setup
cfgprfx=/usr/local/etc/

# Test for configuration file
if [ -n "$cfgprfx$1" ]; then
  if [ -r "$cfgprfx$1" ]; then
    . $cfgprfx$1
  else
    cat $cfgprfx$1
    echo Configuration file $cfgprfx$1 not found or cannot be read
    exit
  fi
else
  echo No configuration file provided
  exit
fi

prefix=/tmp/$su_usr.$$

{ su $su_usr -c "$cmd" 
} 2>$prefix.err 1>$prefix.out

status=$?

if [ $status -ne 0 -o "$mailalways" = "yes" ]; then
{ date
  echo -e "\nCommand:\n$cmd"
  echo -e "\nExit Status:\n$status"
  echo -e "\nStdOut:"
  cat $prefix.out
  echo -e "\nErrOut:"
  cat $prefix.err
  if [ $details = "yes" ]; then
    echo -e "\nFree Memory:"
    free
    echo -e "\nDisk Space:"
    df
  fi
} > $prefix.msg
  mail -s "$subject" $mailto < $prefix.msg
fi

rm $prefix*
