#!/bin/bash

# This must be called from within the src/ai/api directory.

if [ -z "$1" ]; then
	for f in `ls *.hpp `; do
		case "$f" in
			# these files should not be changed by this script
			"ai_controller.hpp" | "ai_object.hpp") continue;
		esac
		awk -f squirrel_export.awk ${f} > ${f}.tmp
		if [ -n "`diff ${f} ${f}.tmp`" ]; then
			mv ${f}.tmp ${f}
			echo "Updated: ${f}"
		else
			rm -f ${f}.tmp
		fi
	done
else
	awk -f squirrel_export.awk $1 > $1.tmp
	if [ -n "`diff $1 $1.tmp`" ]; then
		mv $1.tmp $1
		echo "Updated: $1"
	else
		rm -f $1.tmp
	fi
fi


# Add stuff to ../ai_squirrel.cpp
f='../ai_squirrel.cpp'

functions=``

echo "
{ }
/#define DEFINE_SQUIRREL_CLASS/ {
	squirrel_stuff = \"true\";
	print \"#define DEFINE_SQUIRREL_CLASS\"
	split(\"`grep '^void SQAI.*Register(Squirrel \*engine) {$' *.hpp | sed 's/:.*$//' | sort | uniq | tr -d '\r' | tr '\n' ' '`\", files, \" \")

	for (i = 1; files[i] != \"\"; i++) {
		print \"#include \\\"api/\" files[i] \"\\\"\"
	}

	print \"#undef DEFINE_SQUIRREL_CLASS\"

	next;
}
/^#undef DEFINE_SQUIRREL_CLASS/ { if (squirrel_stuff == \"true\") { squirrel_stuff = \"false\"; next; } }
/^$/ { if (squirrel_stuff == \"true\") { squirrel_stuff = \"false\"; } }
{ if (squirrel_stuff == \"true\") next; }

/\/\* Register all classes \*\// {
	squirrel_stuff = \"true\";
	print \"	/* Register all classes */\"
	print \"	squirrel_register_std(this->engine);\"
	split(\"`grep '^void SQAI.*Register(Squirrel \*engine) {$' *.hpp | sed 's/^.*void //;s/Squirrel \*/this->/;s/ {/;/' | sort  | tr -d '\r' | tr '\n' ' '`\", regs, \" \")

	for (i = 1; regs[i] != \"\"; i++) {
		print \"	\" regs[i]
	}

	next
}

{ print \$0; }
" > ${f}.awk

awk -f ${f}.awk ${f} > ${f}.tmp

if [ -n "`diff ${f} ${f}.tmp`" ]; then
	mv ${f}.tmp ${f}
	echo "Updated: ${f}"
else
	rm -f ${f}.tmp
fi
rm -f ${f}.awk
