#!/bin/awk -f
#$Id: mkprofile,v 1.7 2005/08/19 08:29:04 lioka Exp $

func usage(x)
{
	V["usage/ver"] = "$Revision: 1.7 $"
	match(V["usage/ver"], / [0-9.]+ /)
	print "profile generation utility, v"    \
		substr(V["usage/ver"], RSTART, RLENGTH) "\n\
\n\
Usage: mkprofiles [options] profile\n\
\n\
Valid options are:\n\
  -l xx   use additional package lists with respect to lang xx\n\
          by appending suffix .xx at end of 'file' declaration\n\
  -h      display help screen\n\
\n\
profile sample:\n\
\n\
* profile \"Foo/bar\"\n\
** group \"Baz/Boo\" required file packages/main\n\
description of main group\n\
required -- group will be installed by default\n\
\n\
** group \"Bee\" required file packages/main\n\
blah blah description\n\
another group in profile\n\
\n\
* profile \"ZigZag\"\n\
** group \"Zag/Zig\" optional file packages/main\n\
another profile with one group\n\
descriptions\n\
can\n\
be\n\
multiline\n\
"
	exit(x)
}

BEGIN {
	if (ARGV[1] == "-h") usage(0)
	if (ARGV[1] == "-l" && ARGC > 2) {
		lang = ARGV[2]
		delete ARGV[1]
		delete ARGV[2]
	}

	base = gensub(/[^\/]+$/, "", "", ARGV[1])
	RS="*[[:blank:]]+profile[[:blank:]]+"
	FS="*\\*[[:blank:]]+group[[:blank:]]+"
	
	print "("
}

/^[[:space:]]*$/ { next }

{
	print " (" $1

	saved_RS = RS
	saved_FS = FS

	RS="\n"
	FS=" "

	ngroups = NF + 1
	for (i=2; i < ngroups; i++)
		group[i] = $i

	for (i=2; i < ngroups; i++) {
		if (match(group[i], /^("[^"]+")[[:space:]]+(required|optional)[[:space:]]file[[:space:]]+([[:print:]]+)[^[:print:]]*(.+)$/, g)) {
			print "  (" g[1]
			print "   (state . " g[2] ")"
			print "   (description . \"" gensub(/[[:space:]]+/, " ", "g", g[4]) "\")"

			contents=""
			while ((getline < (base g[3])) > 0) {
				if ($0 ~ /^#/) continue
				contents=contents " " $0
			}
			close(g[3])

			if (lang != "") {
				while ((getline < (base g[3] "." lang)) > 0) {
					if ($0 ~ /^#/) continue
					contents=contents " " $0
				}
				close(g[3] "." lang)
			}

			if (contents == "") {
				print "empty group file '" (base g[3]) "'!" > "/dev/stderr"
				exit 1
			}

			print "   (contents "
			gsub(/[[:space:]]+/, " ", contents)
			gsub(/^[[:space:]]+/, "", contents)
			nc=split(contents, c)
			if (nc == 1)
				print "    \"" contents "\""
			else 
				for (j=1; j<=nc; j++)
					print "    \"" c[j] "\""
			print "    )\n   )"
		}
	}

	print "  )"

	RS = saved_RS
	FS = saved_FS
}

END {
	print " )"
}
