#!/bin/bash

if [ -z "$*" ]; then
	echo "Usage: $0 <vcl files>"
	echo "Example: $0 *.vcl"
	exit 1;
fi
if [ -z "$(which awk)" ] || [ ! -x $(which awk) ]; then
	echo "Can't execute awk"
	exit 1;
fi

if [ -z "$(which dot)" ] || [ ! -x $(which dot) ]; then
	echo "Can't execute dot"
	exit 1;
fi

awk '
/^\s*#/ {
	next;
}
/^\s*sub / {
	tmp = $2;
	gsub("{","",tmp);
	subs[tmp] = tmp;
	filen[tmp] = filen[tmp] " " FILENAME;
	msub = tmp;
}
/^\s*call/ {
	gsub(/;/,"");
	calls[msub] = calls[msub] " " $2;
	callers[$2] = callers[$2] " " msub;
}

/{\s*call/ {
	gsub(/;/,"");
	gsub(/.*{/,"");
	calls[msub] = calls[msub] " " $2;
	callers[$2] = callers[$2] " " msub;
}
/^\s*error/ {
	calls[msub] = calls[msub] " vcl_error";
	callers["vcl_error"] = callers["vcl_error"] " " msub;
}
/^\s*return\s+\(\s*synth/ {
	calls[msub] = calls[msub] " vcl_synth";
	callers["vcl_synth"] = callers["vcl_synth"] " " msub;
}

END {
	print "digraph vcl {"
	for (a in subs) {
		if (match(subs[a],/^vcl_/) != 0) {
			style="color=green style=bold"
		} else {
			style="color=darkgreen";
		}
		print "\t" subs[a] " [label=\"" subs[a] "\\n" filen[subs[a]] "\" " style "];"
		if (calls[subs[a]] == "") {
			if (match(subs[a],/^vcl_/) != 0) {
			} else {
				if (callers[subs[a]] == "")
					print "\t" subs[a] " [color=red];"
			}
		} else {
			split(calls[subs[a]],ar);
			for (x in ar) {
				print "\t" subs[a] " -> " ar[x] #":" x ":" a;
			}
		}
	}
	print "}"
}' $* | dot -Tpng > vcl-visualizer.png
echo "Wrote vcl-visualizer.png"
