ROOT_DIR = ./../..
include $(ROOT_DIR)/multibuild/sdk.mk
include $(ROOT_DIR)/config/config.mk

### Build Android #######################################################
LOCAL_NDK_PATH := $(CONFIG_ANDROID_NDK_PATH)
LOCAL_PROJECTS := pa_nwd_lib pa_driver canary_client
LOCAL_PLATFORM_VERSION := android-28
include $(BUILD_ANDROID)

### Deploy/install targets #####################################################
define enlarge_test_file
  $(eval file_size = $(shell du -m $1 | cut -f1))
  $(shell if [ $(file_size) -lt 50 ]; then head -c 250M < /dev/zero >> $1; fi)
endef

DEVICE_APP_ABI := `adb shell getprop ro.product.cpu.abi`
DEVICE_APP_ABI_32 := armeabi-v7a

.PHONY: _install_nwd_components
_install_nwd_components:
	@adb remount
	@$(ROOT_DIR)/tools/five_push.sh out/android/pa_nwd_lib/$(DEVICE_APP_ABI_32)/ftest_pa_nwd_lib32 --sign -d /vendor/bin
	@if [ ${DEVICE_APP_ABI} = "arm64-v8a" ]; then $(ROOT_DIR)/tools/five_push.sh out/android/pa_nwd_lib/$(DEVICE_APP_ABI)/ftest_pa_nwd_lib \
		--sign -d /vendor/bin ; fi
	@$(ROOT_DIR)/tools/five_push.sh out/$(DEPLOY_TARGET)/ftest_pa_driver/$(DEVICE_APP_ABI)/ftest_pa_driver -d /vendor/bin/
	$(call enlarge_test_file, out/$(DEPLOY_TARGET)/ftest_pending_status/$(DEVICE_APP_ABI)/ftest_pending_status)
	adb shell rm -rf /data/pa && adb shell mkdir -p /data/pa
	@$(ROOT_DIR)/tools/five_push.sh out/$(DEPLOY_TARGET)/ftest_pending_status/$(DEVICE_APP_ABI)/ftest_pending_status -d /data/pa
	adb shell ln -sf /data/pa/ftest_pending_status /vendor/bin/ftest_pending_status
	@adb push out/$(DEPLOY_TARGET)/ftest_weak_status/$(DEVICE_APP_ABI)/ftest_weak_status /data/local/tmp
	@adb shell pa_hmac_signer /data/local/tmp/ftest_weak_status || true

	@cp -f out/$(DEPLOY_TARGET)/canary/$(DEVICE_APP_ABI)/canary out/$(DEPLOY_TARGET)/canary/$(DEVICE_APP_ABI)/canary_only_five
	@$(ROOT_DIR)/tools/five_push.sh out/$(DEPLOY_TARGET)/canary/$(DEVICE_APP_ABI)/canary -d /vendor/bin/
	@$(ROOT_DIR)/tools/five_push.sh out/$(DEPLOY_TARGET)/canary/$(DEVICE_APP_ABI)/canary_only_five -d /vendor/bin/ --five-only
	@$(ROOT_DIR)/tools/five_push.sh ./Makefile -d /data/local/tmp/
	adb shell chmod +x /data/local/tmp/Makefile
	@rm out/$(DEPLOY_TARGET)/canary/$(DEVICE_APP_ABI)/canary_only_five

.PHONY: install
install: _install_nwd_components

### Run/execute targets ########################################################
.PHONY: run_functional_tests
run_functional_tests:
	@echo -e "\tRun functional tests on device"
	@if [ ${DEVICE_APP_ABI} = "arm64-v8a" ]; then adb shell ftest_pa_nwd_lib --gtest_color=yes ; fi
	@sleep 1s
	@adb shell ftest_pa_nwd_lib32 --gtest_color=yes
	@adb shell ftest_pa_driver  --gtest_color=yes --gtest_filter=-*Performance*
	@adb shell ftest_pending_status --gtest_color=yes
	@adb shell /data/local/tmp/ftest_weak_status --gtest_color=yes

### Clean targets ##############################################################
.PHONY: force_clean
force_clean: clean
	@rm -rf out/
