#! /bin/sh

# Greps files in a zip archive.
# Same argument sequence as for grep, except that zip file arguments must be separated
# from flags and patterns by --. If no -- is found in the argument list, returns error.

usage() {
    echo Usage: >&2
    echo $0 "<grep flags> <pattern> -- zipfiles ..." >&2
}

declare -a args

i=0
for (( i=0; $# > 0; i++ ))
do
    if [ "$1" != "--" ]; then
	args[$i]="$1"
	shift
    else
	filesmarked=1
	shift
	break
    fi
done

if [ -z "$filesmarked" ]; then
    Echo "No '--' marker for zipfiles args." >&2
    usage
    exit 1
fi

tmpfile=/tmp/zipgrep$$
rm -rf $tmpfile
mkdir $tmpfile

trap 'rm -rf $tmpfile' EXIT

wd=$(pwd)
cd $tmpfile

while [ $# -gt 0 ]; do
    zipfile="$1"
    zfile="$1"
    shift
    # If zipfile is not absolute, set it relative to wd
    if [ "${zipfile:0:1}" != / ]; then
	zipfile="$wd/${zipfile}"
    fi
    unzip "$zipfile" >/dev/null
    result=$(find . -type f -print0|xargs -0 grep "${args[@]}")
    if [ -n "$result" ]; then
        echo "zip: $zfile"
	echo "$result"
    fi
    cd $wd
    rm -rf $tmpfile
    mkdir $tmpfile
    cd $tmpfile
done
