# -*- coding: iso-8859-1 -*-
# This will create a dist directory containing the executable file, all the data
# directories. All Libraries will be bundled in executable file.
#
# Run the build process by entering 'pygame2exe.py' or
# 'python pygame2exe.py' in a console prompt.
#
# To build exe, python, pygame, and py2exe have to be installed. After
# building exe none of this libraries are needed.

try:
    from distutils.core import setup
    import py2exe, pygame
    from modulefinder import Module
    import glob, fnmatch
    import sys, os, shutil
    import operator
except ImportError, message:
    raise SystemExit,  "Unable to load module. %s" % message


origIsSystemDLL = py2exe.build_exe.isSystemDLL
def isSystemDLL(pathname):
    if os.path.basename(pathname).lower() in ["sdl_ttf.dll"]:
        return 0
    return origIsSystemDLL(pathname)
py2exe.build_exe.isSystemDLL = isSystemDLL

def findMinwiiDir() :
    import minwii
    return os.path.dirname(minwii.__file__)

class MinWii2exe(py2exe.build_exe.py2exe) :
    def copy_extensions(self, extensions) :
        py2exe.build_exe.py2exe.copy_extensions(self, extensions)
        minwiiDir = findMinwiiDir()
        self.copyDataFiles(os.path.join(minwiiDir, 'fonts'), 'minwii/fonts')
        self.copyDataFiles(os.path.join(minwiiDir, 'soundfonts'), 'minwii/soundfonts')
        self.copyDataFiles(os.path.join(minwiiDir, 'widgets', 'data'), 'minwii/widgets/data')

        pygamedir = os.path.dirname(pygame.base.__file__)
        pygame_default_font = os.path.join(pygamedir, pygame.font.get_default_font())
        dest = os.path.join(self.collect_dir, 'pygame', pygame.font.get_default_font())
        self.copy_file(pygame_default_font, dest)
        self.compiled_files.append(os.path.join('pygame', pygame.font.get_default_font()))
    
    def copyDataFiles(self, src, dest) :
        src = src.replace('/', os.path.sep)
        reldest = dest.replace('/', os.path.sep)
        dest = os.path.join(self.collect_dir, reldest)
        
        if not os.path.exists(dest) :
            self.mkpath(dest)
        
        for path, dirs, files in os.walk(src) :
            if '.svn' in path : continue
            relpath = path[len(src)+1:]
            if not os.path.exists(os.path.join(dest, relpath)) :
                self.mkpath(os.path.join(dest, relpath))

            for file in files :
                s = os.path.join(path, file)
                d = os.path.join(dest, relpath, file)
                self.copy_file(s, d)
                print os.path.join(reldest, relpath, file)
                self.compiled_files.append(os.path.join(reldest, relpath, file))
        

class BuildExe:
    def __init__(self):
        #Name of starting .py
        #self.script = "src/minwii/runminwii.py"

        #Name of program
        self.project_name = "MINDs"

        #Project url
        self.project_url = "http://minwii.org"

        #Version of program
        self.project_version = "2.0.2"

        #License of the program
        self.license = "GPL"

        #Auhor of program
        self.author_name = "Samuel Benveniste"
        self.author_email = "samuel.benveniste@gmail.com"
        self.copyright = "Copyright 2010-2011 MINES-ParisTech"

        #Description
        self.project_description = "Musique Interactive Numérique pour les Démences"

        #Icon file (None will use pygame default icon)
        self.icon_file = 'minwii.ico'

        self.data_files = []

        #Extra/excludes python modules
        self.extra_modules = []
        self.exclude_modules = []
        
        #DLL Excludes
        self.exclude_dll = ['']

        #Zip file name (None will bundle files in exe instead of zip file)
        self.zipfile_name = 'minwii_lib.zip'

        #Dist directory
        self.dist_dir ='dist'


    def run(self):
        if os.path.isdir(self.dist_dir): #Erase previous destination dir
            shutil.rmtree(self.dist_dir)
        
        if os.path.isdir('build'): #Clean up build dir
            shutil.rmtree('build')
        
        
        #Use the default pygame icon, if none given
        if self.icon_file == None:
            path = os.path.split(pygame.__file__)[0]
            self.icon_file = os.path.join(path, 'pygame.ico')


        setup(
            cmdclass = {'py2exe': MinWii2exe},
            version = self.project_version,
            description = self.project_description,
            name = self.project_name,
            url = self.project_url,
            author = self.author_name,
            author_email = self.author_email,
            license = self.license,

            # targets to build
            windows = [{
                'script': "src/minwii/runminwii.py",
                'icon_resources': [(0, self.icon_file)],
                'copyright': self.copyright
                },
                {
                'script' : "src/minwii/logapp.py",
                'icon_resources': [(0, 'logapp.ico')],
                'copyright' : self.copyright
                }
                ],
            #console = ["src/minwii/logapp.py"],
            options = {'py2exe': {'optimize': 1,
                                  'bundle_files': 3,
                                  #'compressed': True,
                                  #'excludes': self.exclude_modules,
                                  #'packages': self.extra_modules,
                                  #'dll_excludes': self.exclude_dll,
                                  'skip_archive' : True
                                  }
                      },
            zipfile = self.zipfile_name,
            data_files = self.data_files,
            dist_dir = self.dist_dir
            )
        
        #if os.path.isdir('build'): #Clean up build dir
        #    shutil.rmtree('build')

if __name__ == '__main__':
    if operator.lt(len(sys.argv), 2):
        sys.argv.append('py2exe')
    BuildExe().run() #Run generation
    #raw_input("Press any key to continue") #Pause to let user see that things ends
