#!/bin/bash
#/----------------------------------------------------------------------------------------------\
#|	Summary:			Get and convert trace files from your android device		
#|	Author: 			Ramón L De Jesús				
#|	Start date:			6/5/2013 10:49am						
#|	Last version:		.1.2								
#\ ---------------------------------------------------------------------------------------------/
#
# This script gets selected trace files from a connected android device and:
# 	-	Creates a dir and store this files
# 	-	Converts this files to .dot and .png formats
# 	-	Always save each conversion output to a .txt file 
#
#=====================================================
# Note: Device must be connected. Trace files must be located on the /sdcard/
# 			Script only works on linux machines
#			Tested on a VMWare running Ubuntu 12.04 LTS 64-bit
#=====================================================


# Save username
export user=`eval whoami`

# Save current program PATH
export progPath=`eval pwd`

# Declare traces found
eval tracesFound=0

# Declare sum of all traces found
eval sumOfTraceCycles=0

# -- Functions to call
# Batch run of individual(), according to the amount of files
batch()
{
	eval x=1
	while [ $x -le $2 ] 
	do
		traceNumber=$x
		individual $1$x
		eval x=$(( $x + 1 ))
	done
}

# Creates a dir, gets the file from a connected phone, runs runDmOnTrace()
individual()
{
	if test "$1" != ""
	then	
		#To verify for errors
		old=$tracesFound
		
		#Start file aquisition
		mkdir -p $HOME/Desktop/TraceFiles/$1		
		eval adb pull /sdcard/Traces/$1.trace $HOME/Desktop/TraceFiles/$1/$1.trace >error 2>&1	
		eval rm error
		
		#Calculate process		
		calc=$((traceNumber*100))		
		progress=$(( calc / numberOfTraces ))%	
		
		#Run conversion
		eval runDmOnTrace $1		
						
		#Verify for errors
		if [ $old == $tracesFound ]
		then
			echo -e "\e[1;32m"$1 "Not found!\e[00m"			
			echo -e "	#> \e[1;31m"$progress"\e[00m"
		fi
	fi
}

# if the file exist, run dmtracedump and convert it to its different outputs
runDmOnTrace()
{	
	if [ ! -f $HOME/Desktop/TraceFiles/$1/$1.trace ]
	then
		if [ -d $HOME/Desktop/TraceFiles/$1/ ]
		then
			eval rm -rf $HOME/Desktop/TraceFiles/$1/
	fi
  	else
  		touch $HOME/Desktop/TraceFiles/$1/$1DM.txt
		eval dmtracedump -k -g $HOME/Desktop/TraceFiles/$1/$1DM.png $HOME/Desktop/TraceFiles/$1/$1.trace -t 2 > $HOME/Desktop/TraceFiles/$1/$1DM.txt
	 	eval dmtracedump -o $HOME/Desktop/TraceFiles/$1/$1.trace > $HOME/Desktop/TraceFiles/$1/$1DM_Dump.txt
	  	eval extractTotalCycles $1
	  	echo ""	
	  	echo "========================================================"
		echo ""		
		echo -e $user "your \e[1;32m"$1 "\e[00mtrace results are in "$HOME"/Desktop/TraceFiles/\e[1;32m"$1"\e[00m/"
		echo -e "	>> \e[1;33m"$progress"\e[00m"
		echo ""
		echo "========================================================"
		echo ""
	fi
}

extractTotalCycles()
{
	if [ ! -d $HOME/Desktop/TraceFiles/$traceName-DATA/ ]
	then
		mkdir -p $HOME/Desktop/TraceFiles/$traceName-DATA/
		#For .txt output
		#eval echo TotalCycles>> $HOME/Desktop/TraceFiles/$traceName-DATA/$traceName-TotalCycles.txt
		eval echo TotalCycles >> $HOME/Desktop/TraceFiles/$traceName-DATA/$traceName-TotalCycles.csv
		#eval echo "" >>	$HOME/Desktop/TraceFiles/$traceName-DATA/TotalCycles
	fi
	#displays x
	#eval echo $1 | tr -dc '[0-9]'>> $HOME/Desktop/TraceFiles/$traceName-DATA/TotalCycles
	#displays y
	export cycle=`eval sed -n 3p $HOME/Desktop/TraceFiles/$1/$1DM.txt | tr -dc '[0-9]'`
	#Normal txt	
	#eval echo $cycle >> $HOME/Desktop/TraceFiles/$traceName-DATA/$traceName-TotalCycles.txt
	#Csv ","
	eval echo $cycle >> $HOME/Desktop/TraceFiles/$traceName-DATA/$traceName-TotalCycles.csv
	#Add cycle to sumOfTraceCycles
	let "sumOfTraceCycles += cycle"	
	
	#A trace was found so add it!	
	let "tracesFound += 1"	
}

extractElapsedTime()
{
	eval adb pull /sdcard/Traces/$traceName-ServiceTimes.csv $HOME/Desktop/TraceFiles/$traceName-DATA/$traceName-ServiceTimes.csv
}

VerifyDirAndPrint()
{
	DIR=$HOME"/Desktop/TraceFiles/"
	if [  $tracesFound != 0 ]
	then
		echo -e "Successful find and conversion of \e[1;32m("$tracesFound"/"$numberOfTraces")\e[00m traces."
		eval echo $traceName" runnned in:" >> $HOME/Desktop/TraceFiles/device.txt
     		eval adb get-serialno >> $HOME/Desktop/TraceFiles/device.txt
	else
		eval sleep 3
		if find $HOME/Desktop/TraceFiles/ -maxdepth 0 -empty | read;
		then
			echo "Files not found on TraceFiles."
			echo "Deleting TraceFiles dir..."
			eval rm -rf $HOME/Desktop/TraceFiles/
			eval sleep 3
		fi
		eval clear
		echo -e "\e[1;31m"$tracesFound"\e[00m traces found for trace named: \"\e[1;32m"$traceName"\e[00m\"..."
		echo ""
		echo "|	Please make sure that:"
		echo "|	>- The name of the trace in the device is the name you type."
		echo "|	>- Your phone is properly connected to your computer."		
		echo "|	>- You have properly enable the use of drivers for"
		echo "|	your android device in your linux machine."
		echo "|		# Read more: (http://developer.android.com/tools/device.html)"
		echo "|	>- The option USB Debugging is set to ON, on your phone."
		echo "|  		#Sometimes USB Debugging gets buggy, turn it OFF"
		echo "|  		and ON and then try the script again."
		echo " ==========================="
		echo ""
		eval tryAgain
	fi
}

# -----Calculations
getMean()
{
	eval echo "The mean of \""$traceName"\" is: "$((sumOfTraceCycles/tracesFound))
}

getMedian()
{
	# doesnt work use R for Median
	let "calc= $tracesFound % 2"
	if [ $calc = "1" ]
	then
		let "median= (($tracesFound/2) + (($tracesFound+1)/2))/2"		
	else
		let "median= ($tracesFound/2)"
	fi
	eval echo "The median of \""$traceName"\" is: "$median
}

getMode()
{
	# doesnt work, only displays unique lines in cycles, use R for Mode
	eval echo "The mode of \""$traceName"\" is: "
	eval cat $HOME/Desktop/TraceFiles/$traceName-DATA/TotalCycles | sort | uniq -c 
}


# UI logic execution
UI()
{
	#Verify is old same-trace cycle data is found
	if [ -d $HOME/Desktop/TraceFiles/$traceName-DATA/ ]
	then
		eval rm	-rf $HOME/Desktop/TraceFiles/$traceName-DATA/
	fi
	
	if test "$1" != ""
	then
		echo -e "Converting the trace named: \"\e[1;32m"$1"\e[00m\""		
		if test "$2" != ""
		then
			echo -e "In \"\e[1;32m"$2"\e[00m\" traces"
			eval sleep 3	
			eval batch $1 $2
		else
			eval sleep 3
			eval individual $1
		fi	
	fi
}

#Call plot script
wantPlots()
{
	echo	""
	echo	"-----------------------------------------------------------------"
	echo	""
	echo	"~ P L O T S ~"
	echo	""
	eval read -p "Want_some_plots?_[Y/n]:	" plots
	if test "$plots" == "y" || test "$plots" == "Y" || test "$plots" == ""
	then
		echo $traceName		
		$progPath"/"plotData $traceName
	fi
}

# Try again?
tryAgain()
{
	eval read -p "Trace_again?_[y/N]:	" again
	if test "$again" == "y" || test "$again" == "Y"
	then
		exec $progPath"/"getTraceFiles
	else 
		exit
	fi
}

# -- Run in terminal UI
eval clear
echo	"-------------------------------------------------------------------------------------"
date
echo	""
echo 	"-Gets trace files from your Android Device and outputs their data.-"
echo 	""
echo -e	"* Files will be extracted and stored in\e[1;32m" $HOME"/Desktop/TraceFiles\e[00m"
echo	""
echo	"		Last version:		.1.2"
echo	"" 
echo	"" 
if test "$1" != ""
then
	traceName=$1
	numberOfTraces=$2
	eval UI $1 $2
else

	echo 	$user "Indicate the name and the number of traces to gather."	
	echo	""
	echo	""
	read -p "[traceName]: " userWants	
	read -p	"[numberOfTraces]: " number
	traceName=$userWants
	numberOfTraces=$number
	eval UI $userWants $number
fi
eval VerifyDirAndPrint
echo	"-------------------------------------------------------------------------------------"
echo ">>DONE!"
eval getMean
#eval getMedian
#eval getMode
eval extractElapsedTime
eval wantPlots
eval tryAgain
