#! /bin/sh

meta=;
content=;
ContentCount=0
MetaCount=0

export meta content ContentCount MetaCount
tmpfiles=;

trap '/bin/rm -rf $tmpfiles; exit' 0 1 2 3 15

qtype=all # the default is a complete intersect
export qtype

contentQuery()
{
    ContentCount=`expr $ContentCount + 1`
    (
	lqquery "$1" > $content/$ContentCount &
    ) 2>> $content/.log
}

metaQuery()
{
    MetaCount=`expr $MetaCount + 1`
    (
	lqphrase "$1" > $meta/$MetaCount &
    ) 2>> $meta/.log
}

docontent()
{
    lqrank -r $qtype `ls $content/* | sed 's/^/-f /'` > $content/.all
}

dometa()
{
    lqrank -r all `ls $meta/* | sed 's/^/-f /'` > $meta/.all
}

doboth()
{
    wait
    docontent
    dometa
    wait

    intersect=/tmp/intersect.$$
    tmpfiles="$tmpfiles $intersect"
    lqrank -r all -f $content/.all -f $meta/.all
}

combineQueries()
{
    # We use lqrank to combine queries,
    # and have to put a -f in front of each filename.

    wait
    if test ! -z "$meta"
    then
	if test ! -z "$content"
	then # both
	    doboth
	else # meta only
	    dometa
	    wait
	    cat "$meta/.all"
	fi
    else
	if test ! -z "$meta"
	then # both
	    doboth
	else # content only
	    docontent
	    wait
	    cat "$content/.all"
	fi
    fi
}

for i
do
    case "$i" in
    -meta)
	# the meta data
	meta=/tmp/meta.$$
	tmpfiles="$tmpfiles $meta"
	mkdir $meta
	;;
    -all|-any)
	if test ! -z "$content"
	then
	    echo "usage: `basename $0` -meta stuff -[any|all] stuff" 1>&2
	    exit 1
	fi
	content=/tmp/content.$$
	tmpfiles="$tmpfiles $content"
	mkdir $content
	if [ "$i" = "-any" ]
	then
	    qtype="none" # sent ranking for content
	fi
	;;
    *)
	if test ! -z "$content"
	then
	    contentQuery "$i"
	else
	    metaQuery "$i"
	fi
	;;
    esac
done

wait

combineQueries

if test -f $content/.log
then
    sed "s@^@$content: @" $content/.log
fi

if test -f $meta/.log
then
    sed "s@^@$meta: @" $meta/.log
fi
