#!/bin/sh

# Bzgrep wrapped for bzip2,
# adapted from zgrep by Philippe Troin <[email protected]> for Debian GNU/Linux.
## zgrep notice:
## zgrep -- a wrapper around a grep program that decompresses files as needed
## Adapted from a version sent by Charles Levert <[email protected]>

PATH="/usr/bin:$PATH"; export PATH

prog=`echo $0 | sed 's|.*/||'`
case "$prog" in
       *egrep) grep=${EGREP-egrep}     ;;
       *fgrep) grep=${FGREP-fgrep}     ;;
       *)      grep=${GREP-grep}       ;;
esac
pat=""
while test $# -ne 0; do
 case "$1" in
 -e | -f) opt="$opt $1"; shift; pat="$1"
          if test "$grep" = grep; then  # grep is buggy with -e on SVR4
            grep=egrep
          fi;;
 -A | -B) opt="$opt $1 $2"; shift;;
 -*)      opt="$opt $1";;
  *)      if test -z "$pat"; then
            pat="$1"
          else
            break;
          fi;;
 esac
 shift
done

if test -z "$pat"; then
 echo "grep through bzip2 files"
 echo "usage: $prog [grep_options] pattern [files]"
 exit 1
fi

list=0
silent=0
op=`echo "$opt" | sed -e 's/ //g' -e 's/-//g'`
case "$op" in
 *l*) list=1
esac
case "$op" in
 *h*) silent=1
esac

if test $# -eq 0; then
 bzip2 -cdfq | $grep $opt "$pat"
 exit $?
fi

res=0
for i do
 if test -f "$i"; then :; else if test -f "$i.bz2"; then i="$i.bz2"; fi; fi
 if test $list -eq 1; then
   bzip2 -cdfq "$i" | $grep $opt "$pat" 2>&1 > /dev/null && echo $i
   r=$?
 elif test $# -eq 1 -o $silent -eq 1; then
   bzip2 -cdfq "$i" | $grep $opt "$pat"
   r=$?
 else
   j=$(echo "$i" | sed 's/\\/&&/g;s/|/\\&/g;s/&/\\&/g')
   j=`printf "%s" "$j" | tr '\n' ' '`
   # A trick adapted from
   # https://groups.google.com/forum/#!original/comp.unix.shell/x1345iu10eg/Nn1n-1r1uU0J
   # that has the same effect as the following bash code:
   # bzip2 -cdfq "$i" | $grep $opt "$pat" | sed "s|^|${j}:|"
   # r=${PIPESTATUS[1]}
   exec 3>&1
   eval `
     exec 4>&1 >&3 3>&-
     {
       bzip2 -cdfq "$i" 4>&-
     } | {
       $grep $opt "$pat" 4>&-; echo "r=$?;" >&4
     } | sed "s|^|${j}:|"
   `
 fi
 test "$r" -ne 0 && res="$r"
done
exit $res