#! /usr/bin/env python
"""Straw: A feed aggregator for open source desktops.

Straw is a feed aggregator for open source desktops. Its goal is to be a
faster, easier, and more accessible way to read news and blogs than the
web browser. It uses the Python bindings to the GTK+ toolkit and supports RSS
and ATOM feeds.
"""

classifiers = """\
Development Status :: 4 - Beta
Environment :: X11 Applications :: GTK
Environment :: X11 Applications :: Gnome
Intended Audience :: End Users/Desktop
License :: OSI Approved :: GNU General Public License (GPL)
Operating System :: POSIX
Operating System :: POSIX :: Linux
Programming Language :: Python
Topic :: Desktop Environment
Topic :: Desktop Environment :: Gnome
Topic :: Internet :: WWW/HTTP
"""

import sys
import glob
import os.path

strawenv = {'APPNAME': 'Straw',
            'VERSION': '0.27',
            'PYTHON':  '2.4',
            'PYGTK': (2,8,0)}

if sys.version < strawenv['PYTHON']:
    sys.exit('Error: %s or newer is required. Current version:\n %s'
             % (strawenv['PYTHON'],sys.version))

doclines = __doc__.split("\n")

def modules_check():
    '''Check if necessary modules is installed.
    The function is executed by distutils (by the install command).'''
    # Set This For Machines with No DISPLAY
    nogtk = 0

    import imp
    # Check for PyGTK version
    try:
        import pygtk
        pygtk.require('2.0')
        imp.find_module('gtk')
        import gtk
        if gtk.pygtk_version < strawenv['PYGTK']:
            raise
    except AssertionError:
        pass # We ignore this because gtk must be present to build"
    except RuntimeError, msg:
        if os.environ.get ('DISPLAY', '') != '':
            etype, value, tb = sys.exc_info ()
            traceback.print_exception (etype, value, tb)

            sys.exit('Error: unexpected runtime error checking for gtk module')
	nogtk = 1
        pass # No DISPLAY set, pass
    except:
        sys.exit('Error: PyGTK-%d.%d.%d or newer is required.' % strawenv['PYGTK'])

    # Check other module requirements.
    # In pygtk versions prior to 2.10, gtkhtml2 is included in
    # the 'gnome' module. But as of 2.10, the gtkhtml2 module was
    # removed in 'gnome' and added in 'gnome-extras' module.
    # The egg.trayicon module is also included in g-p-e, so no need to check here.
    mod_list = [
        ('gnome', 'python-gnome2', 0),
        ('gtkhtml2', "python-gnome2-extras", 0),
        ('gconf', "python-gnome2", 1),
        ('bsddb.db', 'python-bsddb', 0),
        ('dbus', 'python-dbus', 0)]

    for m, w, x in mod_list:
	if nogtk == 1 and m == 'gtkhtml2':
	    pass;
	else:
            try:
                if not x: exec('import %s' % m)
                else: imp.find_module(m)
            except ImportError, msg:
                sys.exit("Error: '%s' module in package '%s' is required to install %s" \
                      % (m,w,strawenv['APPNAME']))

    # Check for dbus version
    if getattr(dbus, 'version', None) is None:
        print "Warning: Recent versions of  DBus is needed to run Straw"

    # gtk.glade needs special care (ugly...)
    path = imp.find_module('gtk')
    if not os.path.exists(path[1] + '/glade.so'):
        sys.exit('Error: %s module is required to install %s' \
                 % ("PyGTK's glade", strawenv['APPNAME']))

    # Check for ADNS
    try:
        import adns, ADNS
    except ImportError:
        print 'Warning: ADNS Python module not found, will continue without.'

def translations():
    '''Build mo-po mapping from po directory'''
    trans = []
    dest = 'share/locale/%s/LC_MESSAGES/%s.mo'
    for po in glob.glob('po/*.po'):
        lang = os.path.splitext(os.path.basename(po))[0]
        trans.append((dest % (lang , strawenv['APPNAME'].lower()), po))
    return trans

def translation_files():
    '''Files for translation...'''
    potfile = './po/POTFILES.in'
    if not os.path.exists(potfile):
        sys.exit("No such file, '%s'. This file should've been built \
        automatically. You can run \"intltool-update --pot\" to create it manually.\
        We also encourage you to file a bug report against Straw." % potfile)
    try:
        f = open(potfile)
        files = []
        for line in f:
            # ignore comments and newline
            if not line.startswith('#') or not line.startswith('\n'):
                files.append(line.strip())
    finally:
        f.close()
    return files

def data_files():
    '''Build list of data files to be installed'''
    images = glob.glob('images/*.png')
    misc = [
        'data/default_subscriptions.opml',
        'data/straw.css',
        'glade/straw.glade'
        ]
    files = [
        ('share/pixmaps', ['images/straw.png']),
        ('share/straw', images + misc)]
    return files

# Let distutils do the work
from tools.straw_distutils import setup
setup(name             = strawenv['APPNAME'],
      version          = strawenv['VERSION'],
      description      = doclines[0],
      long_description = "\n".join(doclines[2:]),
      author           = 'Juri Pakaste',
      author_email     = 'juri@iki.fi',
      maintainer       = 'Jan Alonzo',
      maintainer_email = 'jmalonzo@unpluggable.com',
      url              = 'http://www.gnome.org/projects/straw/',
      license          = 'GPL',
      data_files       = data_files(),
      pot_file         = 'po/straw.pot',
      translations     = translations(),
      modules_check    = modules_check,
      msg_sources      = translation_files(),
      desktop_file     = ['straw.desktop.in'],
      constants        = [('constants.py.in', strawenv)],
      scripts          = ['src/straw'],
      packages         = ['straw'],
      package_dir      = {'straw' : 'src/lib'},
      config_files     = [('gconf/schemas',['data/straw.schemas'],
                         'with-gconf-schema-file-dir')],
      classifiers      = filter(None, classifiers.split("\n")))
