BEGIN {
	buildOrder = "";
	MAX_PRETTY_LINE_LEN = 78;
}

function splitLine(text, startingLen, _n, _elem, _offset, _j, _len, _sep)
{
	_n = split(text, _elem, " ");
	_offset = startingLen;
	result = "";
	_sep = "";
	for(_j=1;_j<=_n;_j+=1) {
		_len = length(_elem[_j]) + 1;
		_offset += _len;
		if (_offset > MAX_PRETTY_LINE_LEN) {
			result = result " \\\n\t";
			_offset = _len + 8;
			_sep = "";
		}
		result = result _sep _elem[_j];
		_sep = " ";
	}
	return (result);
}

{
	project = $1
	list = "";
	for(i=2;i<=NF;i+=1) {
		dependent = $i;
		dependencyTree[project,dependent] = dependent;
		list = list " " dependent;
	}
	emitted[project] = 0;
	projectList[project] = list;
}

function emitDependency(target, _i, _n, _a)
{
	if (emitted[target] == 1) {
		return;
	}
	printf("# TARGET %s\n", target);
	emitted[target] = 1;
	_n = split(projectList[target], _a, " ");
	for(_i=1;_i<=_n;_i+=1) {
		printf("# recurse for %s _i=%d\n", _a[_i], _i);
		emitDependency(_a[_i]);
	}
	buildOrder = buildOrder " " target;
	printf(".PHONY: %s\n", target);
	printf("%s: %s\n", target, splitLine(projectList[target],
	       length(target) + 2));
	printf("\tsbmake -C $(STS)/%s\n", target);
	printf("\n");
}

END {
	printf(".PHONY: default everything\n");
	printf("default: everything\n\n");
	#printf(".PHONY:");
	#for (p in projectList) {
	#	printf(" %s", p);
	#}
	printf("\n");
	printf("\n");
	for (p in projectList) {
		emitDependency(p);
	}
	printf("\neverything: %s\n", splitLine(buildOrder, 12));
}
