#!/bin/sh

set -e
#set -x

# MIRROR=/tmp/foo sh grep_for_header.sh Python.h
MIRROR=${MIRROR:-"$HOME/slackware/slackware/slackware64-current/"}
HEADER=${1:-"pam_.*\.h"}

if [ -d "$MIRROR/source/" ] ; then
	MIRROR="$MIRROR/source/"
else
	echo "MIRROR=/tmp/foo/slackware-current/ sh grep_for_header.sh Python.h"
	exit 2
fi

# should result in a string like 
# -name '*.tar.gz'  -o  -name '*.tgz'  -o  -name '*.tar.bz2'  -o  -name '*.tbz'  -o  -name '*.tar.xz'  -o  -name '*.txz'
function find_flags() {
inside=0
for i in \
	tar.gz \
	tgz \
	tar.bz2 \
	tbz \
	tar.xz \
	txz
do
	if [ $inside -eq 1 ] ; then
		echo  -o 
	fi
	echo -name "*.$i" 
	inside=1
done
}


# returns the tar extract to stdout flags, for the file type
function tar_flags() {
case "$1" in
*tbz|*tar.bz2) printf "jxOf";;
*txz|*tar.xz) printf "JxOf";;
*tgz|*tar.gz) printf "zxOf";;
esac
}

for file in $(find $MIRROR -type f $(find_flags)); do
	if [ $(tar $(tar_flags "$file") $file | egrep "include.*$HEADER>" | wc -l ) -gt 0 ] ; then
		echo $file
	fi
done


