ROOT_DIR=./..

include $(ROOT_DIR)/config/config.mk
include $(ROOT_DIR)/multibuild/sdk.mk

### ANDROID PA CLIENT ##########################################################
LOCAL_NAME := android_pa_client
LOCAL_PROJECT_DIR := $(ROOT_DIR)/tests/android/
LOCAL_SDK_PATH := $(CONFIG_ANDROID_SDK_PATH)
LOCAL_NDK_PATH := $(CONFIG_ANDROID_NDK_PATH)
LOCAL_GRADLE_BIN := ./gradlew
include $(BUILD_GRADLE_APK)

.PHONY: install
install: out/gradle/android_pa_client/pa_app-$(DEPLOY_PLATFORM)-debug.apk
	@apk_name=$(<); \
	if [ "${DEPLOY_PLATFORM}" = "qsee" ]; then \
	  is_sys_lib=$$(adb shell ls /system/lib/libQSEEComAPI_system.so); \
	elif [ "${DEPLOY_PLATFORM}" = "tbase" ]; then \
	  is_sys_lib=$$(adb shell ls /system/lib/libTeeClient.so); \
	fi; \
	if [ "$${is_sys_lib}" ]; then  \
		apk_name=out/gradle/android_pa_client/pa_app-$(DEPLOY_PLATFORM)_system-debug.apk; \
	fi; \
	adb install -r $${apk_name}
	@adb shell \
		'if ! grep libpa.so /system/etc/public.libraries.txt > /dev/null; then \
			echo libpa.so >> /system/etc/public.libraries.txt; \
			if [[ -f /system/lib/libQSEEComAPI.so ]]; then \
				lib_name=libQSEEComAPI.so; \
			elif  [[ -f /system/lib/libQSEEComAPI_system.so ]]; then \
				lib_name=libQSEEComAPI_system.so; \
			elif [[ -f /system/lib/libteecl.so ]]; then \
				secure_os_ver=$$(getprop sys.secureos.kernel.version); \
				teegris_ver_patter="2\.[0-9]+\.[0-9]+\.[0-9]+"; \
				if ! echo $$secure_os_ver | grep -E $$teegris_ver_patter > /dev/null; then \
					lib_name=libteecl.so; \
				fi; \
			elif [[ -f /system/lib/libTeeClient.so ]]; then \
				lib_name=libTeeClient.so; \
			elif [[ -f /system/lib/libMcClient.so ]]; then \
				lib_name=libMcClient.so; \
			fi; \
			echo $$lib_name >> /system/etc/public.libraries.txt; \
			reboot; \
		fi'

out/gradle/android_pa_client/pa_app-$(DEPLOY_PLATFORM)-debug.apk:
	@$(MAKE) -f android_pa_client.mk android_pa_client

.PHONY: force_clean
force_clean: clean
	@rm -rfv android/.gradle/
	@rm -rfv android/pa_app/.externalNativeBuild
