#!/bin/sh
#
# safe-pipe - guarantees that piping data through a command which might fail is
# equivalent to piping it through cat (i.e. untouched), rather than just losing
# the data
#
# e.g.
#    wget -o- http://foo.bar/baz.html \
#      | safe-pipe riskily-munge-HTML \
#      | grep foo
#
# its achilles' heel is that it assumes the filter will always play nice
# and return a non-zero exit code on failure, i.e. if no output was generated

tmp=$(mktemp /tmp/safe-pipe.XXXXXX)
cat >>"${tmp}"

# FIXME: save output of risky filter somewhere and only do cat if non-zero
# exit code *and* no output was generated. otherwise we could get two lots of
# output. though maybe that's what we want in some circumstances?
"$@" <"${tmp}" || cat "${tmp}"

rm -- "${tmp}"
