#!/usr/bin/python
VERSION = '2.9.1'

if __name__ == '__main__':
	print 'QTorrent starting up.. Please be patient as this might some time..'
	
	# Hack around stupid problems with global variables and namespace
	import pyqtorrent3, sys
	sys.path = pyqtorrent3.__path__ + sys.path
	pyqtorrent3.__path__ = []
	
	# Try to connect to an already running qtorrent3
	import socket
	from pyqtorrent3 import CONTROLSOCK
	sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
	try:
		sock.connect(CONTROLSOCK)
		sock.close()
		for i in sys.argv[1:]:
			sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
			sock.connect(CONTROLSOCK)
			sock.send(i + "\n")
			sock.close()
		sys.exit(0)
	except socket.error:
		pass
	
	# Import psyco and enable profiling mode
	try:
		import psyco
		psyco.profile()
	except ImportError:
		print 'Note: Psyco not detected, take a peek here: http://psyco.sf.net/'
	
	# Now actually start qtorrent3
	from pyqtorrent3 import run
	run(VERSION)
	
	# Evil haxorism, slaughter lingering threads
	import threading, time
	if hasattr(threading.currentThread(), '_Thread__stop') and threading.activeCount() > 1:
		print 'Giving lingering threads 5 seconds to self-terminate'
		time.sleep(5)
		for t in threading.enumerate():
			if t != threading.currentThread() and hasattr(t, '_Thread__stop'):
				t._Thread__stop()
