#!/bin/bash
#===========================================================================#
# Run programm, and dump it output to stdout only if it returns non-zero    #
# useful utility when run something from cron								#
#===========================================================================#
# (C) Denis Smirnov <mithraen@freesource.info>					  Aug 2009  #
#===========================================================================#
T=`mktemp`
trap 'rm -f -- "$T"' EXIT HUP INT QUIT TERM

TITLE=""

if [ "$1" = "-t" ]; then
	shift;
	TITLE=$1; shift
fi

if [ -z "$1" ]; then
	echo "Use: log-if-exit [-t title] <command> [params]"
	exit -1
fi

PROG=$1; shift

$PROG "$@" >> $T 2>> $T

RC=$?

if [ "$RC" -ne "0" ]; then
	[ -z "$TITLE" ] || echo "$TITLE"
	cat $T
fi
rm -f "$T"
exit $RC

