#!/bin/bash

max_bytes_per_channel=512

temp_stdout=$(tempfile)
temp_stderr=$(tempfile)

"$@" >"$temp_stdout" 2>"$temp_stderr"
exitcode=$?

fold () {
	local tempfile="$1"
	local string=''
	while read line; do
		if [ -n "$string" ]; then
			string="$string / $line"
		else
			string="$line"
		fi
		[ -n "${string:$max_bytes_per_channel}" ] && break
	done <"$tempfile"
	if [ -n "${string:$max_bytes_per_channel}" ]; then
		echo "Output starts with \"${string:0:42}\", but is too long ($( wc -c <"$tempfile" ) bytes) - see $tempfile for details."
	else
		rm -f "$tempfile"
		echo "$string"
	fi
}

stdout=$( fold "$temp_stdout" )
stderr=$( fold "$temp_stderr" )

if [ -n "$stdout" -a -n "$stderr" ]; then
	echo "STDOUT: $stdout; STDERR: $stderr"
elif [ -n "$stdout" ]; then
	echo "$stdout"
elif [ -n "$stderr" ]; then
	echo "STDERR: $stderr"
fi

# sicherheitshalber alles, was nicht explizit als Hard Error gedacht ist,
# in einen Soft Error verwandeln, damit Mails nicht gleich bouncen, sondern
# wir übers Queue-Monitoring mitbekommen, dass es ein Problem gibt, vgl.
# RT#278424:
if [ "$exitcode" = 0 -o "$exitcode" = 100 ]; then
	exit $exitcode
else
	exit 111
fi
