#!/bin/bash

BIBTOOLCMD=""
BIBINPUTFILE=""

######
# HELP
######

Help()
{
	# Display Help
	echo "Searches a BibTeX file using bibtool."
	echo
	echo "Syntax:   dbsearch.sh  [search parameters]"
	echo "  -h       Displays this help"
	echo "  -i FILE  Specify the input file; else runs as a filter"
	echo "  -a RG    List those entries with RG in author list"
	echo "  -t RG    List those entries with RG in title"
	echo "  -k RG    List those entries with RG in keywords"
	echo "  -T TP    List those entries with TP as type"
	echo "  -n RG    List those entries with RG in bib key"
	echo "  -E RG    Search for RG everywhere"
	echo
	echo "Note: RG type arguments can be regexp expressions"
}

######
# Process options
######

while getopts "hi:a:t:k:T:n:E:" option; do
	case $option in
		h) #display help
			Help
			exit;;
		i) BIBINPUTFILE="-i \"$OPTARG\"";;
		a) BIBTOOLCMD="$BIBTOOLCMD | bibtool -- 'select{author \"$OPTARG\"}'";;
		t) BIBTOOLCMD="$BIBTOOLCMD | bibtool -- 'select{title \"$OPTARG\"}'";;
		k) BIBTOOLCMD="$BIBTOOLCMD | bibtool -- 'select{keywords \"$OPTARG\"}'";;
		T) BIBTOOLCMD="$BIBTOOLCMD | bibtool -- 'select{@"$OPTARG"}'";;
		n) BIBTOOLCMD="$BIBTOOLCMD | bibtool -X '$OPTARG'";;
		E) BIBTOOLCMD="$BIBTOOLCMD | bibtool -- 'select{\"$OPTARG\"}'";;
	esac
done

BIBTOOLCMD="bibtool $BIBINPUTFILE $BIBTOOLCMD"
eval $BIBTOOLCMD
