#!/usr/bin/env python

import os
import sys
import glob
import subprocess
from distutils.core import setup
from distutils.command.install_data import install_data
from distutils.command.build import build
from distutils.dep_util import newer
from distutils.log import info


PO_DIR = 'po'
MO_DIR = os.path.join('build', 'mo')

class BuildLocales(build):
  def run(self):
    build.run(self)

    for po in glob.glob(os.path.join(PO_DIR, '*.po')):
      lang = os.path.basename(po[:-3])
      mo = os.path.join(MO_DIR, lang, 'gCue2tracks.mo')

      directory = os.path.dirname(mo)
      if not os.path.exists(directory):
        os.makedirs(directory)

      if newer(po, mo):
        info('compiling %s -> %s' % (po, mo))
        try:
          rc = subprocess.call(['msgfmt', po, '-o', mo])
          if rc != 0:
            raise Warning, "msgfmt returned %d" % rc
        except Exception, e:
          print "Building gettext files failed."
          print "%s: %s" % (type(e), str(e))
          sys.exit(1)

class Install(install_data):
  def run(self):
    self.data_files.extend(self._find_mo_files())
    install_data.run(self)

  def _find_mo_files(self):
    data_files = []
    for mo in glob.glob(os.path.join(MO_DIR, '*', 'gCue2tracks.mo')):
        lang = os.path.basename(os.path.dirname(mo))
        dest = os.path.join('/usr/share', 'locale', lang, 'LC_MESSAGES')
        data_files.append((dest, [mo]))
    return data_files

setup(name = 'gCue2tracks',
        version = '0.4.9',
        description = "Tool for spliting audio CD image to tracks with cue sheet info",
        author = "Denis Fomin",
        author_email = "fominde@gmail.com",
        license = "GNU GPLv2",
        url = "http://trac-hg.assembla.com/gCue2tracks/",
        download_url = "http://trac-hg.assembla.com/gCue2tracks/",
        platforms = ["Linux"],
        cmdclass = {'build': BuildLocales, 'install_data': Install},
        data_files = [("/usr/share/applications", ["gCue2tracks.desktop"]),
                    ("/usr/share/pixmaps", ["ui/gCue2tracks.png"]),
                    ("/usr/share/gcue2tracks", glob.glob('*.py')),
                    ("/usr/share/gcue2tracks/ui", glob.glob('ui/*')),
                    ("/usr/bin", ["gcue2tracks"])]
        )
