#$dirput: round app start_time start_type rss pss ratio pagefault itlbmiss dtlbmiss cpustalled

adb root
adb push perfconf.txt /data/misc/perfetto-configs

if [ $? -ne 0 ]; then
	exit
fi

dir=$(/usr/bin/date +%Y-%m%d-%H%M)
mkdir $dir
mkdir $dir/system_mem
mkdir $dir/traces
echo "round app start_type start_time inc_ratio inc_total rss pss pagefaults itlbmiss dtlbmiss cpustall" > $dir/result

for round in $(seq 1 2); do
	for app in `cat applist`; do
		sleep 3

		# 抓内存相关信息
		adb shell free -h > 			$dir/system_mem/before_free-$app-$round
		adb shell cat /proc/meminfo > 		$dir/system_mem/before_meminfo-$app-$round
		adb shell cat /proc/zoneinfo > 		$dir/system_mem/before_zoneinfo-$app-$round
		adb shell cat /proc/buddyinfo > 	$dir/system_mem/before_buddyinfo-$app-$round
		adb shell cat /proc/pagetypeinfo > 	$dir/system_mem/before_pagetypeinfo-$app-$round
		adb shell cat /proc/vmstat > 		$dir/system_mem/before_vmstat-$app-$round

		./cold_start_app.sh $app $round $dir

		# 回到桌面，应用退后台
		adb shell input keyevent 3

		adb shell free -h > 			$dir/system_mem/after_free-$app-$round
		adb shell cat /proc/meminfo > 		$dir/system_mem/after_meminfo-$app-$round
		adb shell cat /proc/zoneinfo > 		$dir/system_mem/after_zoneinfo-$app-$round
		adb shell cat /proc/buddyinfo > 	$dir/system_mem/after_buddyinfo-$app-$round
		adb shell cat /proc/pagetypeinfo > 	$dir/system_mem/after_pagetypeinfo-$app-$round
		adb shell cat /proc/vmstat > 		$dir/system_mem/after_vmstat-$app-$round

		# 计算启动耗时
		python3 handle_perfetto.py $dir/traces/trace-"$app"-"$round".ptrace mm > tmp.txt
		
		if [ $(cat tmp.txt | wc -l) -ne 1 ]; then
			start_time=0
			start_type="NONE"
		else
			start_time=$(cat tmp.txt | awk '{print $1}')
			start_type=$(cat tmp.txt | awk '{print $2}')
		fi

		start_time=$((start_time/10000))
		start_time=$(echo "scale=2; $start_time / 100" | bc)
		
		# 计算PSS RSS
		if [ $(cat $dir/meminfo-"$app"-"$round".txt | grep "MEMINFO in pid" -c) -ne 1 ]; then
			cat $dir/meminfo-"$app"-"$round".txt | grep "TOTAL PSS" | tail -n 1 > tmp.txt
			pss=$(cat tmp.txt | awk '{print $3}')
			rss=$(cat tmp.txt | awk '{print $6}')
		else
			cat $dir/meminfo-"$app"-"$round".txt | grep "TOTAL PSS" > tmp.txt
			pss=$(cat tmp.txt | awk '{print $3}')
			rss=$(cat tmp.txt | awk '{print $6}')
		fi
		
		pagefaults=$(cat $dir/simpleperf-"$app"-"$round".txt | grep 'page-faults' | awk '{print $4}')
		itlbmiss=$(cat $dir/simpleperf-"$app"-"$round".txt | grep 'iTLB-load-misses' | awk '{print $4}')
		dtlbmiss=$(cat $dir/simpleperf-"$app"-"$round".txt | grep 'dTLB-load-misses' | awk '{print $4}')
		cpustall=$(cat $dir/simpleperf-"$app"-"$round".txt | grep 'raw-stall-backend-mem' | awk '{print $4}')

		# 计算大页相关
		inc_ratio=$(cat $dir/ratio-"$app"-"$round".txt | awk '{print $1}')
		inc_total=$(cat $dir/ratio-"$app"-"$round".txt | awk '{print $2}')
		
		echo $round $app $start_type $start_time $inc_ratio $inc_total $rss $pss $pagefaults $itlbmiss $dtlbmiss $cpustall >> $dir/result

		rm tmp.txt
	done
done
