include Makefile.common

nestedvm_version := 2009-08-09
nestedvm := nestedvm-$(nestedvm_version)

default: test

test: build/org/sqlite/SQLite.class

$(nestedvm)/%:
	$(MAKE) -C $(nestedvm) $*

dl/$(nestedvm).tgz:
	@mkdir -p dl
	cp ../archive/$(nestedvm).tgz $@
#	curl -odl/$(nestedvm).tgz http://nestedvm.ibex.org/dist/$(nestedvm).tgz

dl/$(sqlite)-amal.zip:
	@mkdir -p dl
	curl -odl/$(sqlite)-amal.zip \
	http://www.sqlite.org/sqlite-amalgamation-$(subst .,_,$(sqlite_version)).zip

$(nestedvm)/Makefile: dl/$(nestedvm).tgz
	tar xfz dl/$(nestedvm).tgz


build/SQLite.mips: $(nestedvm)/Makefile $(nestedvm)/env.sh dl/$(sqlite)-amal.zip
	@mkdir -p build
	@mkdir -p build/$(sqlite)-nestedvm
	unzip -qo dl/$(sqlite)-amal.zip -d build/$(sqlite)-nestedvm
	cp ../src/main/java/org/sqlite/Nested*.c build/$(sqlite)-nestedvm
	perl -pi -e "s/sqlite3_api;/sqlite3_api = 0;/g" \
	    build/$(sqlite)-nestedvm/sqlite3ext.h
	# we need a dummy main
	echo 'int main() { return 0; }' >> build/$(sqlite)-nestedvm/sqlite3.c
	# remove utimes
	perl -npe '$$_ =~ s/utimes.*//g;' -i build/$(sqlite)-nestedvm/sqlite3.c 
	# insert a code for loading extension functions
	perl -pi -e "s/^opendb_out:/  if(!db->mallocFailed && rc==SQLITE_OK){ rc = RegisterExtensionFunctions(db); }\nopendb_out:/;" \
	    build/$(sqlite)-nestedvm/sqlite3.c
	cat ext/*.c >> build/$(sqlite)-nestedvm/sqlite3.c
	(. ./$(nestedvm)/env.sh; cd build/$(sqlite)-nestedvm; \
	$$CC -c $$CFLAGS -I. -o sqlite3.o \
	    -DSQLITE_THREADSAFE=0 \
		-DSQLITE_ENABLE_UPDATE_DELETE_LIMIT \
	    -DSQLITE_ENABLE_COLUMN_METADATA \
	    -DSQLITE_CORE \
	    -DSQLITE_ENABLE_FTS3 \
		-DSQLITE_ENABLE_RTREE \
		-DSQLITE_OMIT_LOAD_EXTENSION \
		sqlite3.c; \
	$$CC -c $$CFLAGS -o NestedDB.o Nested*.c)
	./$(nestedvm)/upstream/install/bin/mips-unknown-elf-gcc \
	        -march=mips1 --static \
	        -o $@ build/$(sqlite)-nestedvm/sqlite3.o \
			      build/$(sqlite)-nestedvm/NestedDB.o -lm -lc

build/org/sqlite/SQLite.class: build/SQLite.mips
	java -cp $(nestedvm)/build$(sep)$(nestedvm)/upstream/build/classgen/build \
	    org.ibex.nestedvm.Compiler \
	    -outformat class -d build -o unixRuntime \
	    org.sqlite.SQLite build/SQLite.mips

clean:
	rm -rf build
	rm -rf dist
