include Makefile.common

nestedvm_version := 2007-06-30
nestedvm := nestedvm-$(nestedvm_version)

default: test

test: dist/$(sqlitejdbc)-pure.jar $(test_classes)
	$(JAVA) -cp "dist/$(sqlitejdbc)-pure.jar$(sep)build$(sep)$(libjunit)" \
	    org.junit.runner.JUnitCore $(tests)

dist/$(sqlitejdbc)-pure.jar: build/org/sqlite/SQLite.class $(java_classes)
	@mkdir -p dist
	cd build && jar cf ../$@ \
	    org/sqlite/SQLite.class $(java_classlist) \
	    -C ../$(nestedvm)/build org/ibex

build/org/%.class: src/org/%.java
	@mkdir -p build
	$(JAVAC) -source 1.2 -target 1.2 -classpath "$(nestedvm)/build" \
	    -sourcepath src -d build $<

build/test/%.class: src/test/%.java
	@mkdir -p build
	$(JAVAC) -target 1.5 -classpath "build$(sep)$(libjunit)" \
	    -sourcepath src/test -d build $<

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

dl/$(nestedvm).tgz:
	@mkdir -p dl
	curl -odl/$(nestedvm).tgz http://files.zentus.com/sqlitejdbc/$(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/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

	(. ./$(nestedvm)/env.sh; cd build/$(sqlite)-nestedvm; \
	$$CC -c $$CFLAGS -o sqlite3.o \
	    -DSQLITE_THREADSAFE=0 \
	    -DSQLITE_ENABLE_COLUMN_METADATA \
	    -DSQLITE_CORE \
	    -DSQLITE_ENABLE_FTS3 \
	    -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

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
