import os
import time
import shutil
import subprocess
import sys

toolset = ''
if len(sys.argv) > 1:
	toolset = sys.argv[1]

ret = os.system('cd ../examples && bjam boost=source profile statistics=on -j3 %s stage_client_test' % toolset)
ret = os.system('cd ../examples && bjam boost=source release -j3 %s stage_connection_tester' % toolset)

if ret != 0:
	print 'ERROR: build failed: %d' % ret
	sys.exit(1)

if not os.path.exists('cpu_benchmark.torrent'):
	ret = os.system('../examples/connection_tester gen-torrent -s 10000 -n 15 -t cpu_benchmark.torrent')
	if ret != 0:
		print 'ERROR: connection_tester failed: %d' % ret
		sys.exit(1)

try: shutil.rmtree('t')
except: pass

def run_test(name, test_cmd, client_arg, num_peers):
	output_dir = 'logs_%s' % name
	try: os.mkdir(output_dir)
	except: pass

	port = (int(time.time()) % 50000) + 2000

	try: shutil.rmtree('session_stats')
	except: pass
	try: shutil.rmtree('session_stats_report')
	except: pass

	start = time.time();
	client_cmd = '../examples/client_test -p %d cpu_benchmark.torrent -k -z -H -X -q 120 %s -h -c %d -T %d' \
		% (port, client_arg, num_peers *2, num_peers*2)
	test_cmd = '../examples/connection_tester %s -c %d -d 127.0.0.1 -p %d -t cpu_benchmark.torrent' % (test_cmd, num_peers, port)

	client_out = open('%s/client.out' % output_dir, 'w+')
	test_out = open('%s/test.out' % output_dir, 'w+')
	print client_cmd
	c = subprocess.Popen(client_cmd.split(' '), stdout=client_out, stderr=client_out, stdin=subprocess.PIPE)
	time.sleep(2)
	print test_cmd
	t = subprocess.Popen(test_cmd.split(' '), stdout=test_out, stderr=test_out)

	t.wait()
	c.communicate('q')
	c.wait()

	end = time.time();

	print 'runtime %d seconds' % (end - start)
	print 'analyzing proile...'
	os.system('gprof ../examples/client_test >%s/gprof.out' % output_dir)
	print 'generating profile graph...'
	os.system('python gprof2dot.py <%s/gprof.out | dot -Tps -o %s/cpu_profile.ps' % (output_dir, output_dir))

	os.system('python parse_session_stats.py session_stats/*.log')
	try: shutil.move('session_stats_report', '%s/session_stats_report' % output_dir)
	except: pass
	try: shutil.move('session_stats', '%s/session_stats' % output_dir)
	except: pass

run_test('download', 'upload', '', 50)
run_test('upload', 'download', '-G', 5)


@@ -59,16 +59,43 @@
 rt sys%0A%0A
+cache_size = 300 # in MiB%0A%0A
 toolset 
@@ -220,20 +220,16 @@
 tics=on 
--j3 
 %25s stage
@@ -318,12 +318,8 @@
 ase 
--j3 
 %25s s
@@ -1091,16 +1091,22 @@
 c %25d -T 
+%25d -C 
 %25d' %5C%0A%09%09
@@ -1135,17 +1135,16 @@
 um_peers
- 
 *2, num_
@@ -1150,16 +1150,33 @@
 _peers*2
+, cache_size * 16
 )%0A%09test_
@@ -1911,16 +1911,24 @@
 2dot.py 
+--strip 
 %3C%25s/gpro
@@ -1942,17 +1942,18 @@
  dot -Tp
-s
+ng
  -o %25s/c
@@ -1964,17 +1964,18 @@
 rofile.p
-s
+ng
 ' %25 (out
@@ -2316,12 +2316,13 @@
 , '-G', 
-5
+20
 )%0A%0A

improve benchmark script