VERSION=34.0.0
VERSION_B=$(basename $(basename $(VERSION)))
ANDROID_HOME ?= $(HOME)/Android/Sdk
SDK_TOOLS=$(ANDROID_HOME)
JAVA_PATH=/usr/lib/jvm/java-17-openjdk/bin
JAVAC=$(JAVA_PATH)/javac
JAR=$(JAVA_PATH)/jar
JARSIGNER=$(JAVA_PATH)/jarsigner
KEYTOOL=$(JAVA_PATH)/keytool

ADB=$(SDK_TOOLS)/platform-tools/adb
D8=$(SDK_TOOLS)/build-tools/$(VERSION)/d8
AAPT=$(SDK_TOOLS)/build-tools/$(VERSION)/aapt
ZIPALIGN=$(SDK_TOOLS)/build-tools/$(VERSION)/zipalign
APKSIGNER=$(SDK_TOOLS)/build-tools/$(VERSION)/apksigner

APP=test_reflection
PACKAGE=com.example.theseus.reflection
MAIN_ACTIVITY=MainActivity

JAVAC_ARGS =
D8_ARGS = 

pass=ahahah

export PATH := $(JAVA_PATH):$(PATH)

all: $(shell mkdir -p build)
all: clean build/$(APP).apk
signature_v1: clean build/$(APP).v1.apk

debug: JAVAC_ARGS += -g
debug: D8_ARGS += --debug
debug: all

test: all
	$(ADB) install build/$(APP).apk
	$(ADB) shell am start -n $(PACKAGE)/.$(MAIN_ACTIVITY)

build/%.v1signed.apk: ./build/%.unsigned.apk ./ToyKey.keystore
	$(JARSIGNER) -verbose -keystore ./ToyKey.keystore -storepass $(pass) -keypass $(pass) -signedjar $@ $< SignKey

build/%.v1.apk: ./build/%.v1signed.apk
	$(ZIPALIGN) -v -f 4 $< $@

# TODO: fix dep somehow? cannot find a way to use % or $* in (shell ..)
build/%/classes: $(shell find java/ -type f -regex ".*\.java" )
	mkdir -p ./build/$*/classes
	$(JAVAC) $(JAVAC_ARGS) -d ./build/$*/classes -classpath build/deps.jar:$(SDK_TOOLS)/platforms/android-$(VERSION_B)/android.jar $$(find java/$*/ -type f -regex ".*\.java")

build/%/classes.dex: build/%/classes
	mkdir -p ./build/$*
	$(D8) $(D8_ARGS) --classpath $(SDK_TOOLS)/platforms/android-$(VERSION_B)/android.jar $(shell find build/$*/classes -type f -regex ".*\.class" -printf "'%p'\n") --output ./build/$*/

build/%.unsigned.apk: build/classes/classes.dex
	mkdir -p ./build/$*_files
	mv ./build/classes/classes.dex ./build/$*_files/classes.dex
	$(AAPT) package -v -f -M ./AndroidManifest.xml -I $(SDK_TOOLS)/platforms/android-$(VERSION_B)/android.jar -F $@ ./build/$*_files

build/%.v2aligned.apk: ./build/%.unsigned.apk ./ToyKey.keystore
	$(ZIPALIGN) -v -f 4 $< $@

build/%.apk: ./build/%.v2aligned.apk
	$(APKSIGNER) sign -ks ./ToyKey.keystore --v2-signing-enabled true --in $< --out $@ --ks-pass pass:$(pass)

ToyKey.keystore :
	$(KEYTOOL) -genkeypair -validity 1000 -dname "CN=SomeKey,O=SomeOne,C=FR" -keystore $@ -storepass $(pass) -keypass $(pass) -alias SignKey -keyalg RSA -v

clean:
	$(RM) -r build/*

clean_all: clean
	$(RM) ToyKey.keystore
