# Collect build flags from environment and output -Dvar=val entries
# for compiler invocation line.
# Looks for BLDFLAG* and sets IS_FOR_TARGET from SB_TARGET_ARCH.
# $Id$
# Copyright (C) 2014 - 2018 FARGOS Development, LLC
/BLDFLAG/ {
	eqOff = index($0, "=");
	if (eqOff != 0) {
		var = substr($0, 1, eqOff - 1);
		val = substr($0, eqOff + 1);
		gsub("[.,]", "_", val);
	} else {
		var = $0;
		val = "";
	}
	list[var] = val;
}

# Expect value like Linux.x86_64 or Linux.x86_64,coverage,memsanity
/SB_TARGET_ARCH/ {
	eqOff = index($0, "=");
	val = substr($0, eqOff + 1);
	i = index(val, ".");
	if (i != 0) {
		os = substr(val, 1, i - 1);
		val = substr(val, i + 1);
	} else {
		os = val;
		val = "";
	}
	var = "IS_FOR_TARGET_" os;
	list[var] = "1";
	
	# Value is architecture and options; split on options
	n = split(val, a, ",");
	# generate names like IS_FOR_TARGET_Linux_x86_64 and
	# IS_FOR_TARGET_Linux_coverage
	token = "";
	for (i=1;i<=n;i+=1) {
		# convert any "." into "_" for use in a macro name
		gsub("[.]", "_", a[i]);
		var = "IS_FOR_TARGET_" os "_" a[i];
		list[var] = "1";
	}
	# generate names with all elements, such as
	# IS_FOR_TARGET_Linux_x86_64_coverage
	for (i=1;i<=n;i+=1) {
		if (i == 1) {
			var = "IS_FOR_TARGET_" os;
		}
		gsub("[.]", "_", a[i]);
		var = var "_" a[i];
		list[var] = "1";
	}
}

END {
	sep = "";
	for (v in list) {
		printf("%s-D%s=%s", sep, v, list[v]);
		sep = " ";
	}
	if (sep != "" ) { # something went out
		printf("\n");
	}
}
