# Convert global.def file to .h or .texi format.
# Copyright (C) 2011-2022 Sergey Poznyakoff
#
# Mailfromd is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# Mailfromd is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mailfromd.  If not, see <http://www.gnu.org/licenses/>.

BEGIN {
	if (format == "C") {
		comment[0] = "/*"
		comment[1] = " *"
		comment[2] = " */"
	} else if (format == "texinfo") {
		comment[0] = "@c"
		comment[1] = "@c"
		comment[2] = ""
	} else {
		print "usage: awk -f global.awk -v format={C|texinfo}" > "/dev/stderr"
		exit 1
	}
	print comment[0] " -*- buffer-read-only: t -*- vi: set ro:"
	print comment[1] " THIS FILE IS GENERATED AUTOMATICALLY.  PLEASE DO NOT EDIT."
	if (comment[2]) print comment[2]
	if (format == "C") {
		print "#ifndef __MAILFROMD_GLOBAL_H"
		print "#define __MAILFROMD_GLOBAL_H"
	}
}

END {
	if (format == "C")
		print "#endif"
}

function output(keyword, value) {
	if (format == "C") {
		print "#line",NR,("\"" FILENAME "\"")
		print "#define",keyword,value
	} else if (format == "texinfo") {
		if (match(value,/^".*"$/))
			value = substr(value,2,RLENGTH-2)
		print "@set",keyword,value
	}
}

state == 0 && /^#/ { print comment[0] substr($0,2); state = 1; next }
state == 1 && /^#/ { print comment[1] substr($0,2); next }
state == 1         { if (comment[2]) print comment[2]; state = 0 }	

/^@/ { if (format == "texinfo") print; next }
{ sub(/#.*/,""); }
NF == 0 { next }
{ keyword=$1;
  sub((keyword "[ \t][ \t]*"), "")
  value = $0;
  if (match(value, "`[^`]*`")) {
	  newval = ""
	  do {
		  newval = newval substr(value, 1, RSTART - 1)
		  cmd = substr(value, RSTART+1, RLENGTH-2)
		  while ((cmd | getline) > 0)
			  newval = newval $0
		  close(cmd)
		  value = substr(value, RSTART+RLENGTH)
	  } while (match(value, "`[^`]*`"))
	  value = (newval value)
  } else if (match(value, "^@")) {
	  file = substr(value, 2)
	  while ((getline < file) > 0) {
		  if ($1 == "#define" && $2 == keyword) {
			  sub(("#define " keyword "[ \t][ \t]*"), "")
			  value = $0
			  if (format == "texinfo")
				  output(keyword, value)
			  next
		  }
	  }
	  print FILENAME ":" NR ": definition of " keyword " not found in " file > "/dev/stderr"
	  next
  }
  output(keyword, value)
}
