#!/bin/bash

# crucial file paths
PATH_JAVA_HOME=/opt/jdk1.8.0_91
PATH_ANDROID_SDK=/opt/android-sdk-linux-zaap
PATH_ANDROID_NDK=/opt/android-ndk-r11-linux-x86_64

usage() {
	if [ "$1" != "" ]; then
		echo $1
		echo ""
	fi

	echo "$0 -outdir <output_dir> [-srcdir <source_dir>] [-ut <1|0>]"
	echo "Builds ZEN2 Android Crash Library"
	exit 255;
}

# default property values

SOURCE_DIR=""
OUTPUT_DIR=""
UNIT_TESTS=1

# stores current directory
CURRENTDIR=$(pwd)

# pop shell arguments one by one, while still some exists
while [ $1 ]; do
	argument=$1

	# pops shell argument
	shift

	case "$argument" in

	# -h: help, prints usage
	"-h")
		usage
		;;

	# -help: help, prints usage
	"--help")
		usage
		;;

	"-outdir")
		if [ "$#" == "0" ]; then
			usage "-outdir should have parameter"
		fi

		# create output directory including non-existing parents
        mkdir -p $1

		OUTPUT_DIR=$(readlink -f $1)
		shift
		;;

	"-srcdir")
		if [ "$#" == "0" ]; then
			usage "-srcdir should have parameter"
		fi

		SOURCE_DIR=$(readlink -f $1)
		shift
		;;

	"-ut")
		if [ "$#" == "0" ]; then
			usage "-ut should have parameter"
		fi

		UNIT_TESTS=$1
		shift
		;;

	# default
	*)
		usage "Unknown parameter: $argument"
		;;

	esac
done

if [ "$SOURCE_DIR" == "" ]; then
	SOURCE_DIR=$(readlink -f ${CURRENTDIR})
fi

if [ "$OUTPUT_DIR" == "" ]; then
	usage "-outdir is mandatory parameter"
fi

# prepare Gradle environment
cd ${SOURCE_DIR}
cat <<EOF > local.properties
sdk.dir=${PATH_ANDROID_SDK}
ndk.dir=${PATH_ANDROID_NDK}
EOF

export JAVA_HOME=${PATH_JAVA_HOME}
export ANDROID_HOME=${PATH_ANDROID_SDK}
export PATH=$PATH:${PATH_ANDROID_NDK}

# run Gradle build
echo "Running gradle build"
./gradlew clean buildCrashLibrary

# create output directories
echo "Creating output directories"
mkdir ${OUTPUT_DIR}/aar
mkdir ${OUTPUT_DIR}/apk
mkdir ${OUTPUT_DIR}/jar

# copy results
echo "Copying results (AARs, APKs, JARs)"
for FILE in ${SOURCE_DIR}/build/aar/* ${SOURCE_DIR}/build/jar/* ${SOURCE_DIR}/build/apk/*; do
	cp -r ${FILE} ${OUTPUT_DIR}/$(basename $(dirname ${FILE}))/
done

if [ ${UNIT_TESTS} -gt 0 ]; then
	./gradlew testCrashLibraryDebug testCrashLibraryRelease copyTestResults --continue

	ls -l ${SOURCE_DIR}/build/test-results

	if [ -d ${SOURCE_DIR}/build/test-results ]; then
		echo "Copying unit test results"
		cp -r ${SOURCE_DIR}/build/test-results ${OUTPUT_DIR}/test-results
	else
		echo "Warning: unit tests not found! Either the gradle copy task failed or it didn't run at all!"
	fi
fi
