#!/usr/bin/env python

"""Create, update and compile translation files.

Requires gettext and intltool.
"""

import glob
import optparse
import os

file_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(os.path.abspath(os.path.join(file_dir, "..")))

def compile_data():
    """Compile data files with strings from .po files."""

    path = os.path.join("data", "gaupol.desktop")
    os.system("intltool-merge -d po %s.in %s" % (path, path))
    for path in glob.glob("data/patterns/*.in"):
        os.system("intltool-merge -d po %s %s" % (path, path[:-3]))

def compile_mo(locale):
    """Compile a .mo file for locale."""

    if locale == "all":
        return [compile_mo(x) for x in get_all_locales()]
    po_file = os.path.join("po", "%s.po" % locale)
    mo_dir = os.path.join("locale", locale, "LC_MESSAGES")
    mo_file = os.path.join(mo_dir, "gaupol.mo")
    if not os.path.isdir(mo_dir):
        os.makedirs(mo_dir)
    print "Compiling '%s'..." % mo_file
    os.system("msgfmt -cv %s -o %s" % (po_file, mo_file))

def create_po(locale):
    """Create a new .po file for locale."""

    po_file = os.path.join("po", "%s.po" % locale)
    pot_file = os.path.join("po", "gaupol.pot")
    print "Creating '%s'..." % po_file
    os.system("msginit -l %s -i %s -o %s" % (locale, pot_file, po_file))

def create_pot():
    """Create a new .pot file."""

    pot_file = os.path.join("po", "gaupol.pot")
    if os.path.isfile(pot_file):
        os.remove(pot_file)
    print "Creating '%s'..." % pot_file
    path = os.path.join("data", "gaupol.desktop.in")
    os.system("intltool-extract --type=gettext/ini %s" % path)
    os.system("xgettext -o %s --keyword=N_ -F %s.h" % (pot_file, path))
    os.remove("%s.h" % path)
    for path in glob.glob("data/patterns/*.in"):
        os.system("intltool-extract --type=gettext/ini %s" % path)
        os.system("xgettext -o %s --keyword=N_ -j -F %s.h" % (pot_file, path))
        os.remove("%s.h" % path)
    glade_files = " ".join(glob.glob("data/glade/*.glade"))
    os.system("xgettext -o %s -j -F %s" % (pot_file, glade_files))
    python_files = []
    for (root, dirs, files) in os.walk("gaupol"):
        for name in (x for x in files if x.endswith(".py")):
            python_files.append(os.path.join(root, name))
    python_files = [x for x in python_files if not "test_" in x]
    args = (pot_file, " ".join(python_files))
    os.system("xgettext -o %s --from-code=utf-8 -c -j -F %s" % args)

def get_all_locales():
    """Get a list of all locales in the 'po' directory."""

    return [x[len("po%s" % os.sep):-3] for x in glob.glob("po/*.po")]

def main():
    """Parse arguments and run commands."""

    opts = parse_args()[0]
    if opts.create_pot:
        return create_pot()
    if opts.create_po:
        return create_po(opts.create_po)
    if opts.update_po:
        return update_po(opts.update_po)
    if opts.compile_mo:
        return compile_mo(opts.compile_mo)
    if opts.compile_data:
        return compile_data()
    print "No option given."
    print "Try 'translate --help' for more information."

def parse_args():
    """Parse and return options and arguments."""

    parser = optparse.OptionParser(
        description="Create, update and compile translation files.",
        epilog="LOCALE should be a two or five letter locale code or 'all' " \
            "to process .po files of all locales in the 'po' directory.",
        formatter=optparse.IndentedHelpFormatter(2, 42, None, True),
        usage="translate OPTION")

    parser.add_option(
        "-t", "--create-pot",
        action="store_true",
        dest="create_pot",
        default=False,
        help="create a .pot file")

    parser.add_option(
        "-p", "--create-po",
        action="store",
        type="string",
        metavar="LOCALE",
        dest="create_po",
        default="",
        help="create a .po file for LOCALE")

    parser.add_option(
        "-u", "--update-po",
        action="store",
        type="string",
        metavar="LOCALE",
        dest="update_po",
        default="",
        help="update existing .po file for LOCALE")

    parser.add_option(
        "-m", "--compile-mo",
        action="store",
        type="string",
        metavar="LOCALE",
        dest="compile_mo",
        default="",
        help="compile a .mo file for LOCALE")

    parser.add_option(
        "-d", "--compile-data",
        action="store_true",
        dest="compile_data",
        default=False,
        help="compile data files")

    return parser.parse_args()

def update_po(locale):
    """Update an existing .po files with new strings."""

    if locale == "all":
        return [update_po(x) for x in get_all_locales()]
    po_file = os.path.join("po", "%s.po" % locale)
    pot_file = os.path.join("po", "gaupol.pot")
    print "Updating '%s'..." % po_file
    os.system("msgmerge -U %s %s" % (po_file, pot_file))

main()
