#!/usr/bin/python
import os
import sys
import time
import subprocess
import argparse
import sys
import shutil

#sys.path.append('/home/Research/tools/apktool')
from  pyappinfo.AppPipeline import AppPipeline

result_dir = None
device_port = None


def dynamic_analysis(app_path, pkgname, mainaty):
	print "install", app_path

	os.system('adb -s device-serial wait-for-device install '+ app_path)
	print "installed"
	os.system('adb -s device-serial shell am broadcast -n guard.api.sensitive.ui.sapiguard/guard.api.sensitive.ui.sapiguard.components.PkgChange --es hookpkg '+ pkgname)
	time.sleep(5)
	# # run
	mill = int(round(time.time()))
	# adb -s device-serial shell monkey -p net.sf.times --pct-touch 10 --pct-motion 10 --pct-pinchzoom 5 --pct-trackball 5 --pct-rotation 5 --pct-nav 6 --pct-majornav 5  --pct-appswitch 5 --pct-flip 5  --throttle 500 -v 50

	cmd = "adb -s device-serial shell monkey -p "+pkgname+" --throttle 900 -v 1500"
	os.system(cmd)
	mill2 = int(round(time.time()))
	print "run time(seconds): ",str(mill2 - mill)

	time.sleep(2)
	os.system("adb -s device-serial shell am broadcast -n guard.api.sensitive.ui.sapiguard/guard.api.sensitive.ui.sapiguard.components.PkgChange -a android.intent.action.DB_EXTRACTED")


	app_result_dir = os.path.join(result_dir, pkgname)
	if os.path.exists(app_result_dir):
		shutil.rmtree(app_result_dir)
	os.makedirs(app_result_dir)


	app_api_db = os.path.join(app_result_dir, 'sapiguard.db') 
	app_screenshots = os.path.join(app_result_dir, 'screenshots') 
	time.sleep(5)

	os.system("adb -s device-serial pull /storage/emulated/0/sapiguard/sapiguard.db " + app_api_db)
	os.system("adb -s device-serial pull /sdcard/sapiguardSS " + app_screenshots)
	
	os.system("adb -s device-serial uninstall "+pkgname)
	# print "uninstalled"
	# time.sleep(3)
	
	os.system("echo "+pkgname+" >> ./out.txt")

def analysis_apps(app_info_db):
	db_pipeline = AppPipeline(app_info_db)
	db_pipeline.initialize()
	app_infos = db_pipeline.get_all_apps_apppath_pkgname_mainaty_perms()
	db_pipeline.finalize()

	index = 0
	for info in app_infos:
		app_path,pkgname,mainaty,perms = info
		if   perms is None :
			os.system("echo "+pkgname+" >> ./out_none_perms.txt")
			continue
		# if  "net.sf.times" != pkgname:
		# 	continue
		index +=1
		print index
		if index < 500:
			continue
		print app_path
		dynamic_analysis(app_path,pkgname,mainaty) 


#python ./main.py -appinfodb /home/Research/tools/apktool/results/fdroid_28_9_2018.db -devicePort device-serial 
if __name__ == "__main__":
	#process arguments
	parser = argparse.ArgumentParser(prog = 'python main.py', description = 'execute app on the phone and collect sensitive api info at runtime')
	parser.add_argument('-appinfodb', nargs = 1, help = 'specify the path of the db file which includes apk paths', default = ['/home/Research/tools/apktool/results/fdroid_28_9_2018.db'])
	parser.add_argument('-resultdir', nargs = 1, help = 'specify the directory of the file saving results of the analysis', default = ['/home/Research/results/'])
	parser.add_argument('-devicePort', nargs = 1, help = 'android device port', default = ['device-serial'])

	args = parser.parse_args()


	if args.appinfodb is None or args.devicePort is None:
		parser.print_help()
		sys.exit()

	app_info_db = args.appinfodb[0]
	device_port = args.devicePort[0]
	result_dir = args.resultdir[0]

	analysis_apps(app_info_db)
	