.DEFAULT_GOAL := native

ZIRAN ?= ziran
PYTHON ?= python3
CC ?= cc
BUILD := build
BASELINE := $(BUILD)/baseline
UPSTREAM := $(CURDIR)/upstream
VARINT := $(BUILD)/varint-c
SQLITE_LINK := -lm -ldl -pthread
SANITIZERS := -fsanitize=address,undefined -fno-sanitize-recover=all -fno-omit-frame-pointer
OPTFLAGS ?= -O2 -g
TCL_CONFIG ?=
TCLSH ?=
TEST_JOBS ?= 2

.PHONY: native check test-varint test-compat upstream-test amalgamation

native: amalgamation
	$(MAKE) -C $(BASELINE) sqlite3 libsqlite3.a libsqlite3.so

amalgamation: $(BASELINE)/Makefile
	$(MAKE) -C $(BASELINE) sqlite3.c

$(BASELINE)/Makefile: Makefile $(UPSTREAM)/configure $(UPSTREAM)/auto.def $(UPSTREAM)/VERSION
	mkdir -p $(BASELINE)
	cd $(BASELINE) && "$(UPSTREAM)/configure" --disable-tcl --disable-readline \
		--enable-fts5 --enable-static --enable-shared

check: test-varint test-compat
	$(ZIRAN) check --locked

# Only the test oracle sees SQLite's internal functions. The shipped libraries
# keep the standard upstream symbol visibility and never link the Ziran code.
test-varint: $(BUILD)/varint-oracle.o
	$(ZIRAN) build --project --locked --target=c -o $(VARINT) src/Varint.zi
	$(CC) $(CPPFLAGS) $(OPTFLAGS) -I$(VARINT) tests/varint_test.c $(VARINT)/Varint.c \
		$(BUILD)/varint-oracle.o $(LDFLAGS) $(SQLITE_LINK) -o $(BUILD)/varint-test
	$(BUILD)/varint-test
	$(CC) $(CPPFLAGS) $(OPTFLAGS) $(SANITIZERS) -fno-pie -no-pie -I$(VARINT) \
		tests/varint_test.c $(VARINT)/Varint.c $(BUILD)/varint-oracle.o \
		$(LDFLAGS) $(SQLITE_LINK) -o $(BUILD)/varint-test-sanitized
	$(BUILD)/varint-test-sanitized

# The amalgamation submake runs before this rule and updates its compiler input.
$(BASELINE)/sqlite3.c: amalgamation
	@test -f "$@"

$(BUILD)/varint-oracle.o: tests/varint_oracle.c $(BASELINE)/sqlite3.c
	$(CC) $(CPPFLAGS) $(OPTFLAGS) -I$(BASELINE) -c $< -o $@

test-compat: native
	$(PYTHON) tests/compatibility.py $(BASELINE)/sqlite3 $(UPSTREAM)/manifest.uuid $(BUILD)

upstream-test:
	mkdir -p $(BUILD)/upstream-test
	cd $(BUILD)/upstream-test && "$(UPSTREAM)/configure" --dev --disable-readline --enable-fts5 \
		$(if $(TCL_CONFIG),--with-tcl="$(TCL_CONFIG)") $(if $(TCLSH),--with-tclsh="$(TCLSH)")
	$(MAKE) -C $(BUILD)/upstream-test verify-source srctree-check sourcetest coretestprogs
	cd $(BUILD)/upstream-test && TZ=UTC ./testfixture "$(UPSTREAM)/test/testrunner.tcl" veryquick -j $(TEST_JOBS)
