#!/usr/bin/env python
import os, sys
from optparse import OptionParser
import pygtk; pygtk.require('2.0')

__builtins__._ = lambda x: x

parser = OptionParser(usage="usage: %prog [options] interface [args]")
parser.add_option("", "--before", help="choose a version before this", metavar='VERSION')
parser.add_option("-c", "--cache", help="show the cache", action='store_true')
parser.add_option("-d", "--download-only", help="fetch but don't run", action='store_true')
parser.add_option("-m", "--main", help="name of the file to execute")
parser.add_option("-n", "--no-self-update", help="don't check for updates to the GUI itself", action='store_true')
parser.add_option("", "--not-before", help="minimum version to choose", metavar='VERSION')
parser.add_option("-r", "--refresh", help="check for updates of all interfaces", action='store_true')
parser.add_option("-s", "--source", help="select source code", action='store_true')
parser.add_option("-v", "--verbose", help="more verbose output", action='count')
parser.add_option("-V", "--version", help="display version information", action='store_true')

parser.disable_interspersed_args()

(options, args) = parser.parse_args()

if options.verbose:
	import logging
	logger = logging.getLogger()
	if options.verbose == 1:
		logger.setLevel(logging.INFO)
	else:
		logger.setLevel(logging.DEBUG)

if options.cache:
	# Must fork before importing gtk, or ATK dies
	if os.fork():
		# We exit, so our parent can call waitpid and unblock.
		sys.exit(0)
	# The grandchild continues...

import gui

if options.version:
	print "0launch-gui (zero-install) " + gui.version
	print "Copyright (C) 2005 Thomas Leonard"
	print "This program comes with ABSOLUTELY NO WARRANTY,"
	print "to the extent permitted by law."
	print "You may redistribute copies of this program"
	print "under the terms of the GNU General Public License."
	print "For more information about these matters, see the file named COPYING."
	sys.exit(0)

import gtk

if not hasattr(gtk, 'combo_box_new_text'):
	import combo_compat

gtk.rc_parse_string('style "scrolled" { '
		    'GtkScrolledWindow::scrollbar-spacing = 0}\n'
		    'class "GtkScrolledWindow" style : gtk "scrolled"\n')

if options.cache:
	import cache
	cache_explorer = cache.CacheExplorer()
	cache_explorer.show()
	cache_explorer.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))
	gtk.gdk.flush()
	cache_explorer.populate_model()
	cache_explorer.window.set_cursor(None)
	gtk.main()
	sys.exit(0)

if len(args) < 1:
	parser.print_help()
	sys.exit(1)

interface_uri = args[0]
prog_args = args[1:]

from zeroinstall.injector import model, autopolicy, namespaces

if options.no_self_update is not True:
	gui_policy = autopolicy.AutoPolicy(namespaces.injector_gui_uri)
	if gui_policy.need_download():
		# Need to refresh the GUI itself first!
		prog_args = ['--no-self-update']
		if options.source:
			prog_args += ['--source']
			options.source = False
		if options.main:
			prog_args += ['--main', options.main]
			options.main = None
		prog_args += sys.argv[1:]

		interface_uri = namespaces.injector_gui_uri
		options.download_only = False
		options.refresh = True

restrictions = []
if options.before or options.not_before:
	restrictions.append(model.Restriction(model.parse_version(options.before),
					      model.parse_version(options.not_before)))

policy = gui.GUIPolicy(interface_uri, prog_args,
		   download_only = bool(options.download_only),
		   refresh = bool(options.refresh),
		   main = options.main,
		   src = options.source,
		   restrictions = restrictions)
policy.main()
