#!/bin/bash
#
# This script tries to pull gprof profiling information generated by aFreeRDP
# from the target using adb and generating human readable profiling data from
# it.
#
# Any arguments supplied to the script will be appended to adb.
#
# Requirements:
#  - ANDROID_SDK is set to the android SDK directory or adb is in path.
#

if [ -d $ANDROID_SDK ]; then
	ADB=$ANDROID_SDK/platform-tools/adb
else
	ADB=`which adb`
fi

GCC=@CMAKE_C_COMPILER@
GPROF=${GCC/gcc/gprof}
LIB=@PROJECT_BINARY_DIR@/client/Android/FreeRDPCore/jni/armeabi-v7a/libfreerdp-android.so

if [ ! -f $LIB ]; then
	echo "Missing libfreerdp-android.so"
	echo "Please build the project first."
	exit -1
fi

if [ ! -f $GPROF ]; then
	echo "gprof could not be found at $GPROF."
	echo "Please assure, that you are using a GCC based android toolchain."
	exit -2
fi

if [ ! -f $ADB ] || [ ! -x $ADB ]; then
	echo "adb could not be found."
	echo "assure, that either ANDROID_SDK is set to the path of your android SDK"
	echo "or that adb is in path."
	exit -3
fi

# Do the actual work in a temporary directory.
SRC=`mktemp -d`
cd $SRC
$ADB $@ pull /sdcard/gmon.out
if [ ! -f gmon.out ]; then
	echo "Could not pull profiling information from device!"
	RC=-4
else
	echo "Pulled profiling information from device, starting conversion..."
	$GPROF $LIB -PprofCount -QprofCount -P__gnu_mcount_nc -Q__gnu_mcount_nc
	RC=0
fi
rm -rf $SRC

exit $RC
