#!/usr/bin/env python

# This file is part of Window-Switch.
# Copyright (c) 2009-2013 Antoine Martin <antoine@nagafix.co.uk>
# Window-Switch is released under the terms of the GNU GPL v3
import glob
import os.path
import sys
import traceback

prefix = os.getenv("PREFIX", "/usr")

scripts = glob.glob("./skel/bin/*")
data_files = []
#cant run nautilus on macos/win:
if not sys.platform.startswith("darwin") and not sys.platform.startswith("win"):
	nautilus_lib="%s/lib/nautilus" % prefix
	#the test below only works if the python-nautilus (aka nautilus-python) is installed!
	#TODO: figure out what is the correct way of knowing where the extensions go for the distro
	#IMO python extensions can be platform independent so /usr/lib should be looked up no matter what
	if os.path.exists("%s/lib64/nautilus" % prefix):
		nautilus_lib="%s/lib64/nautilus" % prefix
	etc_prefix = "/etc"
	if prefix!="/usr":
		etc_prefix = "%s/etc" % prefix			#ie: /usr/local/etc on FreeBSD
	data_files = [
				("%s/winswitch/" % etc_prefix, glob.glob("./skel/etc/winswitch/*")),
				("%s/extensions-2.0/python/" % nautilus_lib, ["winswitch/fs/nautilus_winswitch.py"])
			]
elif sys.platform.startswith("win"):
	scripts = []
	# ModuleFinder can't handle runtime changes to __path__, but win32com uses them
	try:
		# if this doesn't work, try import modulefinder
		import py2exe.mf as modulefinder
		import win32com
		for p in win32com.__path__[1:]:
			modulefinder.AddPackagePath("win32com", p)
		for extra in ["win32com.shell"]: #,"win32com.mapi"
			__import__(extra)
			m = sys.modules[extra]
			for p in m.__path__[1:]:
				modulefinder.AddPackagePath(extra, p)
	except ImportError:
		print("Ensure that py2exe is installed!")
		# no build path setup, no worries.
		traceback.print_exc()

if not sys.platform.startswith("win"):
	libexec_dir="%s/libexec" % prefix
	if not os.path.exists(libexec_dir):
		libexec_dir="%s/lib" % prefix
	files = glob.glob("./skel/libexec/winswitch/*")
	files.remove("./skel/libexec/winswitch/bin-override")
	data_files.append(("%s/winswitch" % libexec_dir, files))
	files = glob.glob("./skel/libexec/winswitch/bin-override/*")
	data_files.append(("%s/winswitch/bin-override" % libexec_dir, files))


#Add all /skel/share to data files:
def add_dir(data_files, root, d):
	dir_path = os.path.join(root, d)
	files = os.listdir(dir_path)
	real_files = []
	for f in files:
		file_path = os.path.join(dir_path, f)
		if os.path.isdir(file_path):
			if f!=".svn":
				add_dir(data_files, root, os.path.join(d, f))	#recurse down
		else:
			real_files.append(file_path)
	data_files.append((d, real_files))
#Add recursively all files under ./skel as if they were under PREFIX/share:
if not sys.platform.startswith("win"):
	add_dir(data_files, "./skel", "share")


#import is delayed until after py2exe (does trickery with modulefinder)
from distutils.core import setup
from winswitch import __version__


print("sys.argv=%s" % str(sys.argv))
sys.path.insert(0, os.getcwd())
try:
	from winswitch import add_build_info
	add_build_info.main()
except Exception, e:
	print("failed to update build_info: %s" % e)

packages=['winswitch', 'winswitch.fs', 'winswitch.objects', 'winswitch.util', 'winswitch.net', 'winswitch.ui', 'winswitch.server', 'winswitch.client', 'winswitch.virt', 'winswitch.sound', 'winswitch.twisted']
install_requires=['pycrypto', 'twisted', 'netifaces', 'pam', 'pyasn1']


#not included by default in python 2.4:
#ie: (2, 6, 2, 'final', 0)
(major, minor, _, _, _) = sys.version_info
if major!=2:
	print("WARNING: this software has not been tested with python versions outside 2.x!")
elif minor<=5:
	print("WARNING: python version 2.5 and older are no longer supported, please upgrade!")
	if minor<5:
		install_requires.append("uuid")
		install_requires.append("ctypes")
		install_requires.append("hashlib")


#platform specific: py2app/py2exe
extra_options = {}
setup_requires = []
includes = []
def add_std_includes():
	#used by win32 and darwin:
	global includes
	includes += ["cairo", "pango", "pangocairo", "atk", "gobject", "gtk.keysyms",
				"hashlib", "netifaces"]
	includes += ["OpenGL", "OpenGL_accelerate"]
	includes += ["pyasn1", "zope.interface", "numpy", "PIL"]
	includes += ["Crypto", "Crypto.Cipher"]
	#twisted:
	includes += ["twisted.conch", "twisted.conch.ssh", "twisted.conch.openssh_compat",
				 "twisted.conch.client", "twisted.internet", "twisted.python",
				 "twisted.protocols", "zope.interface"]
	#xpra generic:
	includes += ["xpra", "xpra.scripts", "xpra.scripts.main"]
	#xpra gtk2:
	for x in ("client", "border_client_window", "custom_client_window",
			  "debuginfo_client_window", "gtk2_notifier",
			  "topbar_client_window", "tray_menu"):
		includes.append("xpra.client.gtk2."+x)
	#xpra codecs:
	for x in ("csc_cython", "csc_swscale", "dec_avcodec2", "enc_proxy", "argb", "vpx", "enc_x264", "webp", "xor"):
		includes.append("xpra.codecs."+x)
	#xpra platform:
	for x in ("features", "gui", "info", "keyboard", "options", "paths", "shadow_server"):
		includes.append("xpra.platform."+x)
		includes.append("xpra.platform."+sys.platform+"."+x)

if sys.platform.startswith("darwin"):
	import py2app	#@UnresolvedImport
	assert py2app is not None
	setup_requires.append('py2app')
	Plist = dict(CFBundleDocumentTypes=[dict(CFBundleTypeExtensions=["wsw"],
										 CFBundleTypeName="Winswitch Server Config",
										 CFBundleTypeRole="Viewer"),
									]
			 )
	#packages.append('CoreFoundation')
	#packages.append('AppKit')
	add_std_includes()
	extra_options = dict(
		app=["./winswitch/client/applet_wrapper.py"],
		install_requires=install_requires,
		options={'py2app': {
		'iconfile': './osx/winswitch_applet.icns',
		'plist': Plist,
		'site_packages': False,
		'argv_emulation': True,
		'strip': False,
		"frameworks": ['CoreFoundation', 'Foundation', 'AppKit'],
		"includes":   includes}})
	includes += ["glib", "gio",
				#"CoreFoundation",
				 "winswitch.util.gst_launch_wrapper", "pygst", "gst"]
elif sys.platform.startswith("win"):
	import py2exe	#@UnresolvedImport
	assert py2exe is not None
	windows = [		{'script': 'winswitch/client/applet.py',			'icon_resources': [(1, "winswitch.ico")],		"dest_base": "Window-Switch",},
					{'script': 'winswitch/fs/open_remotely.py',			'icon_resources': [(1, "winswitch_star.ico")],	"dest_base": "WinSwitch-Open",},
				]
	console = [
					{'script': 'winswitch/server/server_wrapper.py',	'icon_resources': [(1, "winswitch.ico")],		"dest_base": "Switch-Server",},
					{'script': 'winswitch/util/server_portinfo.py',		'icon_resources': [(1, "winswitch.ico")],		"dest_base": "Server-PortInfo",},
				]
	excludes = (
				"xpra.xposix", "xpra.darwin", "parti",
				#Tcl/Tk
				"Tkconstants", "Tkinter", "tcl",
				#PIL bits that import TK:
				"_imagingtk", "PIL._imagingtk", "ImageTk", "PIL.ImageTk", "FixTk",
				#formats we don't use:
				"GimpGradientFile", "GimpPaletteFile", "BmpImagePlugin", "TiffImagePlugin",
				#not used on win32:
				"mmap",
				#this is a mac osx thing:
				"ctypes.macholib",
				#not used:
				"curses", "email", "pdb", "tty",
				"ssl", "_ssl",
				"cookielib", "BaseHTTPServer", "ftplib", "fileinput",
				"distutils", "setuptools", "doctest")

	add_std_includes()
	includes += ["win32",
				"win32con", "win32gui", "win32process", "win32pdh", "win32ui", "win32api", "wmi"]
	try:
		import pygst
		import gst
		assert gst is not None and pygst is not None
		print("python-gst found, adding gst_tcp_audio to build")
		includes.append("pygst")
		includes.append("gst")
		includes.append("gst.extend")
	except ImportError, e:
		print("python-gst not found, disabled gst_tcp_audio build!")

	webp_ENABLED = True
	if webp_ENABLED:
		webp_DLL = "C:\\libwebp-windows-x86\\bin\\libwebp.dll"
		data_files.append(('', [webp_DLL]))

	extra_options = dict(
		#app="winswitch/client/applet.py",
		options={'py2exe': {
				'unbuffered': True,
				#'optimize': 0,
				#'compressed': 0,
				#'packages': ['encodings', 'netifaces', 'win32com'],
				#'bundle_files': 1,
				#'dll_excludes': ["MSVCP90.dll", ],
				'packages': ['encodings'],
				'includes': includes,
				'excludes': excludes,
				}},
		windows = windows,
		console = console,
	)
	# prepare the InnoSetup winswitch.iss script (not using fileinput module as this is for win32...):
	f = file("./winswitch.iss", "r")
	newlines = []
	for line in f.readlines():
		if '%VERSION%' in line:
			line = line.replace("%VERSION%", __version__)
		newlines.append(line)
	f.close()

	outfile = file("./winswitch.iss", 'w')
	outfile.writelines(newlines)


print("setup_requires=%s" % str(setup_requires))
print("install_requires=%s" % str(install_requires))
print("extra_options=%s" % str(extra_options))



setup(name='winswitch',
	version=__version__,
	description='Window-Switch: Virtual Desktop Sharing',
	author="Antoine Martin",
	author_email='antoine@nagafix.co.uk',
	url='http://winswitch.org/',
	download_url='http://winswitch.org/downloads/',
	packages=packages,
	license='GPL3',
	scripts = scripts,
	data_files = data_files,
	platforms = ('Any',),
	classifiers = [
		"Development Status :: 5 - Production/Stable",
		"Intended Audience :: Developers",
		"Intended Audience :: End Users/Desktop",
		"Intended Audience :: Information Technology",
		"License :: OSI Approved :: GNU General Public License (GPL)",
		"Programming Language :: Python",
		"Operating System :: OS Independent",
	],
	**extra_options
	)
