#! /usr/bin/env python
#
# Copyright (C) 2012 Nuxeo
#

import os
import sys
from datetime import datetime

from distutils.core import setup

scripts = ["nuxeo-drive-client/bin/ndrive"]
freeze_options = {}

name = 'nuxeo-drive'
packages = [
    'nxdrive',
    'nxdrive.tests',
    'nxdrive.gui',
    'nxdrive.protocol_handler',
    'nxdrive.data',
    'nxdrive.data.icons',
]
package_data = {
    'nxdrive.data.icons': ['*.png', '*.svg', '*.ico', '*.icns'],
}
script = 'nuxeo-drive-client/bin/ndrive'
icons_home = 'nuxeo-drive-client/nxdrive/data/icons'
win_icon = os.path.join(icons_home, 'nuxeo_drive_icon_64.ico')
png_icon = os.path.join(icons_home, 'nuxeo_drive_icon_64.png')
osx_icon = os.path.join(icons_home, 'nuxeo_drive_app_icon_128.icns')

if sys.platform == 'win32':
    icon = win_icon
elif sys.platform == 'darwin':
    icon = osx_icon
else:
    icon = png_icon

icons_files = []
for filename in os.listdir(icons_home):
    filepath = os.path.join(icons_home, filename)
    if os.path.isfile(filepath):
        icons_files.append(filepath)

version = '0.1.0'

if '--dev' in sys.argv:
    # timestamp the dev artifacts for continuous integration
    # distutils only accepts "b" + digit
    sys.argv.remove('--dev')
    timestamp = datetime.utcnow().isoformat()
    timestamp = timestamp.replace(":", "")
    timestamp = timestamp.replace(".", "")
    timestamp = timestamp.replace("T", "")
    timestamp = timestamp.replace("-", "")
    version += "b" + timestamp

includes = [
    "PySide",
    "PySide.QtCore",
    "PySide.QtNetwork",
    "PySide.QtGui",
    "atexit",  # implicitly required by PySide
    "sqlalchemy.dialects.sqlite",
]

if '--freeze' in sys.argv and sys.platform == 'win32':
    print "Building standalone executable..."
    sys.argv.remove('--freeze')
    from cx_Freeze import setup, Executable

    # build_exe does not seem to take the package_dir info into account
    sys.path.append('nuxeo-drive-client')

    executables = [Executable(script, base=None)]

    if sys.platform == "win32":
        # Windows GUI program that can be launched without a cmd console
        executables.append(
            Executable(script, targetName="ndrivew.exe", base="Win32GUI",
                       icon=icon, shortcutDir="ProgramMenuFolder",
                       shortcutName="Nuxeo Drive"))
    scripts = []
    # special handling for data files
    packages.remove('nxdrive.data')
    packages.remove('nxdrive.data.icons')
    package_data = {}
    data_home = 'nuxeo-drive-client/nxdrive/data'
    include_files = [
        (data_home + "/icons/nuxeo_drive_icon_%d.png" % i,
         "icons/nuxeo_drive_icon_%d.png" % i)
        for i in [16, 32, 48, 64]
    ]
    freeze_options = dict(
        executables=executables,
        options={
            "build_exe": {
                "includes": includes,
                "packages": packages + [
                    "nose",
                ],
                "excludes": [
                    "ipdb",
                    "clf",
                    "IronPython",
                    "pydoc",
                    "tkinter",
                ],
                "include_files": include_files,
            },
            "bdist_msi": {
                "add_to_path": True,
                "upgrade_code": '{800B7778-1B71-11E2-9D65-A0FD6088709B}',
            },
        },
    )
    # TODO: investigate with esky to get an auto-updateable version but
    # then make sure that we can still have .msi and .dmg packages
    # instead of simple zip files.

elif sys.platform == 'darwin':
    # Under OSX we use py2app instead of cx_Freeze because we need:
    # - argv_emulation=True for nxdrive:// URL scheme handling
    # - easy Info.plit customization
    import py2app  # install the py2app command

    freeze_options = dict(
        app=["nuxeo-drive-client/bin/ndrive.py"],
        data_files=[('icons', icons_files)],
        options=dict(
            py2app=dict(
                iconfile=osx_icon,
                argv_emulation=False,  # We use QT for URL scheme handling
                plist=dict(
                    CFBundleDisplayName="Nuxeo Drive",
                    CFBundleName="Nuxeo Drive",
                    CFBundleIdentifier="org.nuxeo.drive",
                    LSUIElement=True,  # Do not launch as a Dock application
                    CFBundleURLTypes=[
                        dict(
                            CFBundleURLName='Nuxeo Drive URL',
                            CFBundleURLSchemes=['nxdrive'],
                        )
                    ]
                ),
                includes=includes,
            )
        )
    )

setup(
    name=name,
    version=version,
    description="Desktop synchronization client for Nuxeo.",
    author="Nuxeo",
    author_email="contact@nuxeo.com",
    url='http://github.com/nuxeo/nuxeo-drive',
    packages=packages,
    package_dir={'nxdrive': 'nuxeo-drive-client/nxdrive'},
    package_data=package_data,
    scripts=scripts,
    long_description=open('README.rst').read(),
    **freeze_options
)

@@ -1675,36 +1675,8 @@
 argv
- and sys.platform == 'win32'
 :%0A  
@@ -2447,20 +2447,21 @@
  %7B%7D%0A    
-data
+icons
 _home = 
@@ -2492,16 +2492,22 @@
 ive/data
+/icons
 '%0A    in
@@ -2525,67 +2525,53 @@
  = %5B
-%0A        (data_home +
+(os.path.join(icons_home, f),
  %22
-/
 icons/
-nuxeo_drive_icon_%25d.png
+%25s
 %22 %25 
-i,
+f)
 %0A   
@@ -2580,45 +2580,12 @@
     
-%22icons/nuxeo_drive_icon_%25d.png%22 %25 i)%0A
+    
     
@@ -2596,34 +2596,35 @@
 for 
-i
+f
  in 
-%5B16, 32, 48, 64%5D%0A    
+os.listdir(icons_home)
 %5D%0A  

include new systray icons in windows freeze