#!/usr/bin/env python
#
# Cohoba - a GNOME client for Telepathy
#
# Copyright (C) 2006 Collabora Limited
#
# This package is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This package is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public
# License along with this package; if not, write to the Free Software
# Foundation, 51 Franklin Street, Fifth Floor, Boston, MA, 02110-1301 USA.


import getopt, sys
from os.path import exists, isdir, isfile, join, dirname, abspath

def usage():
	print """=== Cohoba: Usage
$ cohoba-applet [OPTIONS] component

OPTIONS:
	-h, --help			Print this help notice.
	-w, --window		Launch the applet in a standalone window for test purposes (default=no).
	-t, --trace			Use tracing.
	-m, --mode			Applet mode, one of 'group', 'main', 'contact' (default='main').
	          			When runing 'houston', you can use 'accounts' to display accounts.
	-d, --debug			Enable debug output.
	"""
	sys.exit()

# --------Start Bootstrap code ---------
# Allow to use uninstalled
def _check(path):
	return exists(path) and isdir(path) and isfile(path+"/AUTHORS")

name = join(dirname(__file__), '..')
if _check(name):
	print 'Running uninstalled cohoba, modifying PYTHONPATH'
	sys.path.insert(0, abspath(name))
else:
	sys.path.insert(0, abspath("@PYTHONDIR@"))
	print "Running installed cohoba, using [@PYTHONDIR@:$PYTHONPATH]"

# Now the path is set, import our stuff
import cohoba, cohoba.defs, dbus, dbus.glib, logging

import gettext, locale
gettext.bindtextdomain('cohoba', abspath(join(cohoba.defs.DATA_DIR, "locale")))
if hasattr(gettext, 'bind_textdomain_codeset'):
	gettext.bind_textdomain_codeset('cohoba','UTF-8')
gettext.textdomain('cohoba')

# Macosx doesn't seem to have locale.*
if hasattr(locale, 'bindtextdomain'):
	locale.bindtextdomain('cohoba', abspath(join(cohoba.defs.DATA_DIR, "locale")))
if hasattr(locale, 'bind_textdomain_codeset'):
	locale.bind_textdomain_codeset('cohoba','UTF-8')
if hasattr(locale, 'textdomain'):
	locale.textdomain('cohoba')

# -------- End bootstrap code-----------

def set_killall_name(name):
	try:
		# attempt to set a name for killall
		import ctypes
		libc = ctypes.CDLL('libc.so.6')
		# 15 = PR_SET_NAME from linux/prctl.h
		libc.prctl(15, name, 0, 0, 0)
	except Exception, e:
		print "Notice: Unable to set process name: %s" % e
		
# Nice dialog to show uncaught exceptions
import cohoba.gtkexcepthook

def start_applet(standalone, mode):
	from cohoba import COHOBA_APPLET_MODE_MAIN, COHOBA_APPLET_MODE_GROUP, COHOBA_APPLET_MODE_CONTACT, COHOBA_APPLET_MODE_ME
	from cohoba.CohobaFactory import CohobaFactory
	
	factory_callback = lambda applet, iid: CohobaFactory().make_applet(applet, iid, COHOBA_APPLET_MODE_MAIN)
	if mode == "group":
		factory_callback = lambda applet, iid: CohobaFactory().make_applet(applet, iid, COHOBA_APPLET_MODE_GROUP)
	elif mode == "contact":
		factory_callback = lambda applet, iid: CohobaFactory().make_applet(applet, iid, COHOBA_APPLET_MODE_CONTACT)
	elif mode == "me":
		factory_callback = lambda applet, iid: CohobaFactory().make_applet(applet, iid, COHOBA_APPLET_MODE_ME)
	elif mode != None:
		print 'Applet mode must be in: main, group, contact, me:', mode
		usage()
	
	if mode == None:
		name = "cohoba"
	else:
		name = "cohoba-%s" % mode
		
	if standalone:
		print 'Runing applet in standalone window'
		standalone_window(factory_callback, name)
		run(do_trace)
	else:
		print 'Starting cohoba factory'
		make_applet(factory_callback, name)


def make_applet(factory_callback, name):
	set_killall_name(name)
	
	import gnomeapplet
	gnomeapplet.bonobo_factory(
		"OAFIID:Cohoba_Factory",
		gnomeapplet.Applet.__gtype__,
		cohoba.defs.PACKAGE,
		cohoba.defs.VERSION,
		factory_callback)

# Return a standalone window that holds the applet
def standalone_window(factory_callback, name):
	set_killall_name(name)
	
	import gnome, gtk, gnomeapplet

	gnome.init(cohoba.defs.PACKAGE, cohoba.defs.VERSION)
		
	app = gtk.Window(gtk.WINDOW_TOPLEVEL)
	app.set_title("Cohoba")
	app.connect("destroy", gtk.main_quit)
	app.set_property('resizable', False)
	
	applet = gnomeapplet.Applet()
	applet.get_orient = lambda: gnomeapplet.ORIENT_DOWN
	
	factory_callback(applet, None)

	applet.reparent(app)		
	app.show_all()
	
	return app

def houston(mode):
	set_killall_name("cohoba-houston")
	
	from cohoba.houston.Houston import Houston
	h = Houston()
	
	if mode == "accounts":
		h.ShowAccounts()
	
	return h.disconnect
	
def technobabble():
	set_killall_name("cohoba-technobabble")
	
	from cohoba.technobabble.TechnoBabbleChannelHandler import TechnoBabbleChannelHandler
	TechnoBabbleChannelHandler()
	
	from cohoba.bigbrother.BigBrotherChannelHandler import BigBrotherChannelHandler
	BigBrotherChannelHandler()

def run(do_trace, interrupt_callback=None):
	import gtk, gobject
	
	# run the new command using the given trace
	if do_trace:
		import trace
		trace = trace.Trace(
			ignoredirs=[sys.prefix],
			ignoremods=['sys', 'os', 'getopt', 'libxml2',
				'gettext', 'posixpath', 'locale', 'UserDict'],
			trace=True,
			count=False)
		trace.run('__import__("gtk").main()')
	else:
		try:
			gtk.main()
		except KeyboardInterrupt:
			if interrupt_callback!= None:
				def idle():
					interrupt_callback()
					gtk.main_quit()
				gobject.idle_add(idle)
				gtk.main()
			else:
				raise
		
if __name__ == "__main__":
	standalone = False
	do_trace = False
	mode = None
	component = "applet"
	
	try:
		opts, args = getopt.getopt(sys.argv[1:], "dhwtm:", ["debug", "help", "window", "trace", "mode"])
	except getopt.GetoptError:
		# Unknown args were passed, we fallback to bahave as if
		# no options were passed
		opts = []
		args = sys.argv[1:]
	
	for o, a in opts:
		if o in ("-h", "--help"):
			usage()
		elif o in ("-w", "--window"):
			standalone = True
		elif o in ("-t", "--trace"):
			do_trace = True
		elif o in ("-m", "--mode"):
			mode = a
		elif o in ("-d", "--debug"):
			cohoba.LOGGING_LEVEL = logging.DEBUG
			
	if len(args) >= 1 and not args[0].startswith("-"):
		component = args[0]
	
	print 'Runnin with options:', {
		'standalone': standalone,
		'do_trace': do_trace,
		'mode': mode,
		'component': component,
	}, 'Other arguments are:', args
	
	if component == "applet":
		start_applet(standalone, mode)
	elif component == "houston":
		print 'Running houston mision control'
		run(do_trace, houston(mode))
	elif component == "technobabble":
		print 'Running technobabble'
		technobabble()
		run(do_trace)
	else:
		print 'Error: Unknown component, try one of:\n\tapplet, houston, technobabble'
		usage()
