1#!/usr/bin/awk -f
2
3# Usage: foo <template> <file>
4# Searches through file for instances of 'kern_return_t $FOO'
5# where $FOO is an line in the template file
6# and prepends the first line in the template file.
7
8# Example template format:
9#       %{
10#       __WATCHOS_PROHIBITED
11#       %}
12#       act_get_state
13#       thread_get_state
14#
15
16# BEGIN { print ARGV[1]; print ARGV[2] }
17
18# In the first file, build array of lines
19NR==FNR && /^ *$/ {
20	next
21}
22NR==FNR && /^#/ {
23	next
24}
25NR==FNR && /%{/ {
26	parse_prefix = 1
27	prefix = ""
28	next
29}
30NR==FNR && /^%}/ {
31	parse_prefix = 0
32	next
33}
34NR==FNR {
35	if (parse_prefix && length(prefix)) {
36		prefix = sprintf("%s\n%s", prefix, $0)
37	} else if (parse_prefix) {
38		prefix = $0
39	} else if (length(templates[$0])) {
40		templates[$0] = sprintf("%s\n%s", templates[$0], prefix)
41	} else {
42		templates[$0] = prefix
43	}
44	next
45}
46
47# In the second file, match kern_return_t <template>
48# at the beginning of the line
49# print the prefix line if found
50
51/^kern_return_t/ {
52#	print "match"
53	if ($2 in templates) {
54		print templates[$2]
55	}
56}
57
58# Pass through everything in the second file
59{ print }
60