#!/bin/sh
#
# find QA tests that use a QA archive $1 $2 ...
# $1, $2, ... are assumed to be either <basename> or <dir>/<basename>
# for archives
#
# archive matches are:
# - appear in a non-comment line surrounded by whitespace, or ^, or $, or
#   some character with special shell syntax, like |, ;, &, <, > or
#   pathname components / or .
#

tmp=${TMPDIR:-/tmp}/find-archive-$$
trap "rm -f $tmp.*; exit 0" 0 1 2 3 15

all=false
list=false
while [ $# -gt 0 ]
do
    case "$1"
    in
	-a)
	    all=true
	    shift
	    ;;
	-l)
	    list=true
	    shift
	    ;;
	*)
	    break
	    ;;
    esac
done

if [ $# -eq 0 ]
then
    echo >&2 "Usage: find-archive [-a] [-l] archive [...]"
    exit 1
fi

archive_pat=`echo "$*" | sed -e 's/ /|/g'`
sep_pat='[   |;&<>./,"]'

# first (and always) all of the QA test scripts
#
grep -E "(^|$sep_pat)($archive_pat)($|$sep_pat)" [0-9][0-9][0-9] [0-9][0-9][0-9][0-9] >$tmp.lines

if [ ! -s $tmp.lines ]
then
    echo >&2 "Info: ${archive_pat}: not used in any test"
else
    # now hunt for any duals (like valgrind) where some other
    # test runs the matching test ... this is a transitive use
    # of the archive
    #
    rm -f $tmp.trans
    for seq in `sed <$tmp.lines -e 's/:.*//' | sort | uniq`
    do
	grep -E "^\./$seq( |\$)" [0-9][0-9][0-9] [0-9][0-9][0-9][0-9] >>$tmp.trans
    done
    if [ -s $tmp.trans ]
    then
	sort -t ':' -k1,1 $tmp.lines $tmp.trans >$tmp.tmp
	mv $tmp.tmp $tmp.lines
    fi
    if $list
    then
	cat $tmp.lines
    else
	sed <$tmp.lines -e 's/:.*//' \
	| sort -n \
	| uniq >$tmp.out
	echo `cat $tmp.out`
    fi
fi

if $all
then
    # the QA makefiles and any of the scripts in the archives
    # where directories are hiding
    #
    rm -f $tmp.lines
    find archives badarchives -type f \
    | while read f
    do
	case "$f"
	in
	    *.meta|*.index|*.[0-9])
		;;

	    *.meta.xz|*.index.xz|*.[0-9].xz)
		;;

	    *.meta.bz2|*.index.bz2|*.[0-9].bz2)
		;;

	    *)
		grep -E "(^|$sep_pat)($archive_pat)($|$sep_pat)" "$f" \
		| sed -e "s;^;$f:;" >>$tmp.lines
		;;
	esac
    done
    # and the .out files
    #
    grep -E "(^|$sep_pat)($archive_pat)($|$sep_pat)" [0-9][0-9][0-9].out* [0-9][0-9][0-9][0-9].out* \
    | sed -e '/\.out\.bad:/d' >>$tmp.lines
    if [ -s $tmp.lines ]
    then
	if $list
	then
	    cat $tmp.lines
	else
	    sed <$tmp.lines -e 's/:.*//' \
	    | sort -n \
	    | uniq
	fi
    else
	echo >&2 "Info: ${archive_pat}: not used in any archive script"
    fi
fi
