#!/usr/bin/awk -f
#
# Copyright (c) 2015 Matthias Kilian <kili@openbsd.org>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# Search a cvs changelog (as in /cvs/CVSROOT/ChangeLog) for certain
# regexps in certain parts of the changelog. Arguments are given in the
# form `match:regexp[:...', where `match' determines which part of the
# changelog are matched against `regexp'. The following match types are
# supported:
#
# - block:	the whole changelog entry
# - cvsroot:	the cvsroot field of the entry
# - module:	the cvs module of the entry
# - author:	the author of the entry
# - date:	the date of the entry
# - vendor:	the vendor tag (for newly imported files)
# - tag:	the branch tag (if any)
#
# if multiple match/regexp pairs are given, they are logically and'ed,
# i.e. all regexps must match.

function usage()
{
	print "usage: clgrep match:regex[:match:regex...] [file ...]" > "/dev/stderr"
	exit 1
}


BEGIN {
	vmatches["block"] = 1
	vmatches["cvsroot"] = 1
	vmatches["module"] = 1
	vmatches["author"] = 1
	vmatches["date"] = 1
	vmatches["vendor"] = 1
	vmatches["tag"] = 1
	matchcount = split(ARGV[1], matchres, ":")
	ARGV[1] = ""
	if (matchcount % 2 || !matchcount)
		usage()
	for (i = 1; i <= matchcount; i += 2)
		if (matchres[i] in vmatches)
			matchr[matchres[i]] = matchres[i + 1]
		else
			usage()
		
}

function pblock(	p, m)
{
	if (block) {
		p = 1
		for (m in matchr)
			if (m == "block" && block !~ matchr[m] ||
			    m == "cvsroot" && cvsroot !~ matchr[m] ||
			    m == "module" && module !~ matchr[m] ||
			    m == "author" && author !~ matchr[m] ||
			    m == "date" && date !~ matchr[m] ||
			    m == "vendor" && vendor !~ matchr[m] ||
			    m == "tag" && tag !~ matchr[m]) {
				p = 0
				break
		}
		if (p)
			print block
		block = ""
		cvsroot = ""
		module = ""
		author = ""
		date = ""
		vendor = ""
		tag = ""
	}
}

END {
	pblock()
}

/^CVSROOT:/ {
	pblock()
	block = $0
	cvsroot = $NF
	next
}

/^Module name:/ {
	module = $NF
}

/^Changes by:/ {
	author = $3
	date = $4 " " $5
}

/^[[:space:]]*Vendor Tag:/ {
	vendor = $3
}

/: Tag:/ {
	tag = $0
	sub(/.*: Tag:[[:space:]]*/, "" tag)
	sub(/[[:space:]].*/, "" tag)
}

{
	block = block "\n" $0
}
