#!/usr/bin/env python
# Copyright(C) 2007, David Aguilar <davvid@gmail.com>
# License: GPL v2 or later
import os
import sys
import optparse
from os.path import join
from os.path import dirname
from os.path import realpath
from distutils.sysconfig import get_python_version

def setup_environment():
	"""Prepends sys.path with ugit's module path."""
	# ex: sys.path = [ ..., /usr/share ]
	#     from ugit import utils
	# implies: utils = /usr/share/ugit/utils.py
	ugit   = realpath(sys.argv[0])
	bin    = dirname(ugit)
	prefix = dirname(bin)
	share  = join(prefix,'share')
	sys.path.insert(0, share)

	# Look in both 2.4 and 2.5 directories but give preference to
	# the currently running version.
	sitepackages24 = join(prefix, 'lib', 'python2.4', 'site-packages')
	sitepackages25 = join(prefix, 'lib', 'python2.5', 'site-packages')

	python_version = get_python_version()
	if python_version == '2.5':
		sys.path.insert(0, sitepackages24)
		sys.path.insert(0, sitepackages25)
	else:
		sys.path.insert(0, sitepackages25)
		sys.path.insert(0, sitepackages24)

def main():
	# cmdline
	parser = optparse.OptionParser(
			usage='%prog /repo/path-1 ... /repo/path-N*\n\n'
			+'*the current directory is used when no '
			+'paths are specified.''')
	parser.add_option('-v', '--version',
			help='Show ugit version',
			dest='version',
			default=False,
			action='store_true')
	opts, args = parser.parse_args()

	# allow "git ugit /path/to/repo"
	if args:
		os.chdir(os.path.realpath(args[0]))

	# This sets up sys.path so that the ugit modules can be found.
	setup_environment()

	if opts.version:
		from ugit.version import VERSION
		print "ugit version", VERSION
		sys.exit(0)

	# allow "git ugit /repo/path-1 .. /repo/path-N
	from ugit.models import Model
	from ugit import utils
	from ugit.views import View
	from ugit.controllers import Controller

	if args[1:]:
		for repo in [ os.path.realpath(r) for r in args[1:] ]:
			utils.fork("git", "ugit", repo)

	# load the model right away so that we can bail out if
	# when no git repo exists
	model = Model()

	# qt
	try:
		from PyQt4 import QtCore
		from PyQt4 import QtGui
	except ImportError:
		print "Sorry, you do not seem to have PyQt4 installed."
		print "Please install it before using ugit."
		print "e.g.:    sudo apt-get install python-qt4"
		sys.exit(-1)

	app = QtGui.QApplication(sys.argv)
	app.setWindowIcon(QtGui.QIcon( utils.get_icon('git.png')) )
	locale = str(QtCore.QLocale().system().name())
	qmfile = utils.get_qm_for_locale( locale )
	if os.path.exists(qmfile):
		translator = QtCore.QTranslator()
		translator.load(qmfile)
		app.installTranslator(translator)
	# simple mvc
	view = View(app.activeWindow())
	ctl = Controller(model, view)
	view.show()
	sys.exit(app.exec_())

if __name__ == "__main__":
	main()
