#!/usr/bin/env python

from os import listdir, path
from distutils.core import setup
from DistUtilsExtra.command import *
import sys
import subprocess

dist = setup(name='gvb',
      version='1.2',
      description='Good ViBrations',
      license='GPL',
      author='Pietro Battiston',
      author_email='toobaz@email.it',
      url='http://www.pietrobattiston.it/gvb',
      scripts=['gvb'],
      packages=['gvbmod'],
      data_files=[('share/gvb/stuff', ['stuff/logo.svg', 'stuff/wlogo.svg', 'stuff/gvb.glade']),
#				  ('share/doc/gvb', ['README']),
				  ('share/pixmaps', ['stuff/gvb.svg']),
				  ('share/applications', ['stuff/gvb.desktop'])]+
				  [('share/locale/'+lang+'/LC_MESSAGES/', ['locale/'+lang+'/LC_MESSAGES/gvb.mo'] ) for lang in listdir('locale')],
      cmdclass = { "build" :  build_extra.build_extra,
                   "build_help" :  build_help.build_help},
      classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Environment :: X11 Applications :: GTK',
        'Intended Audience :: Education',
        'Intended Audience :: End Users/Desktop',
        'License :: OSI Approved :: GNU General Public License (GPL)',
        'Operating System :: POSIX :: Linux',
        'Programming Language :: Python',
        'Topic :: Education :: Testing',
        'Topic :: Scientific/Engineering :: Physics',
        'Topic :: Scientific/Engineering :: Visualization',
        ]    
     )

if 'install' in dist.command_options:
    if 'prefix' in dist.command_options['install']:
        prefix = dist.command_options['install']['prefix'][1]
    else:
        prefix = sys.prefix
    
    # "prefix" usually starts with a "/", which disturbs our "path.join()"s below:
    net_prefix = prefix[prefix.startswith('/'):]
    
    if 'root' in dist.command_options['install']:
        root = dist.command_options['install']['root'][1]
    else:
        root = '/'
    
    omf_path, omf_files = filter(lambda x : 'help/C/gvb-C.omf' in x[1], dist.data_files)[0]
    
    for omf in omf_files:
        folder, lang, filename = omf.split('/')
        help_path, help_file = filter(lambda x: 'help/%s/gvb.xml' % lang in x[1], dist.data_files)[0]
        omf_full_path = path.join(root, net_prefix, omf_path, filename)
        help_full_path = path.join(prefix, help_path, 'gvb.xml')
        try:
            assert (not subprocess.call(['scrollkeeper-preinstall', help_full_path, omf_full_path, omf_full_path]))
        except:
            print 'Trying with "/usr/local" (do not worry about last error message, unless it is repeated below).'
            omf_full_path = omf_full_path.replace('usr/share', 'usr/local/share')
            help_full_path = help_full_path.replace('usr/share', 'usr/local/share')
            subprocess.call(['scrollkeeper-preinstall', help_full_path, omf_full_path, omf_full_path])
#        print ['scrollkeeper-preinstall', help_full_path, omf_full_path, omf_full_path]
