#!/usr/bin/python2
# -*- coding: ISO-8859-1 -*-
# Copyright (C) 2006 Juan David Ibez Palomar <jdavid@itaapy.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

# Import from the Standard Library
from datetime import datetime
from optparse import OptionParser
import os
import sys

# Import from itools
import itools
from itools.uri.generic import Path
from itools.resources import get_resource, memory
from itools.handlers import get_handler
import itools.gettext
from itools.xhtml import XHTML
import itools.stl



def get_commit_metadata(reference):
    lines = os.popen('git-cat-file commit %s' % reference).readlines()
    # The commit id
    commit_id = lines[0].strip().split()[1]
    # The author
    author = None
    for line in lines:
        if line.startswith('author'):
            author = line
    if author is None:
        raise ValueError, ("cannot find the commit author, "
            "please report the output of 'git-cat-file commit %s'" % reference)
    # The timestamp
    timestamp = datetime.fromtimestamp(int(author.strip().split()[-2]))

    return commit_id, timestamp



def get_version():
    # Find out the current branch
    for line in os.popen('git-branch').readlines():
        if line.startswith('*'):
            branch_name = line[2:-1]
            break
    else:
        return None

    # Look for tags
    cmd = 'git-ls-remote -t . %s*' % branch_name
    tags = [ x.strip().split('/')[-1] for x in os.popen(cmd).readlines() ]

    # And the version name is...
    if tags:
        tags.sort()
        version_name = tags[-1]
    else:
        version_name = branch_name

    # Get the timestamp
    head_id, head_timestamp = get_commit_metadata('HEAD')
    tag_id, tag_timestamp = get_commit_metadata(version_name)

    if not tags or tag_id != head_id:
        timestamp = head_timestamp.strftime('%Y%m%d%H%M')
        return '%s-%s' % (version_name, timestamp)

    return version_name



if __name__ == '__main__':
    # The command line parser
    version = 'itools %s' % itools.__version__
    description = ('Builds the package.')
    parser = OptionParser('%prog',
                          version=version, description=description)

    options, args = parser.parse_args()
    if len(args) != 0:
        parser.error('incorrect number of arguments')

    # Initialize the list of files to install (the MANIFEST)
    manifest = ['MANIFEST']
    cmd = 'git-ls-files'
    for path in os.popen(cmd).readlines():
        path = path.strip()
        if not os.path.islink(path):
            manifest.append(path)

    # Get languages to translate
    languages = []
    cmd = 'find locale -name "*.po"'
    for path in os.popen(cmd).readlines():
        path = path.strip()
        languages.append(path[7:-3])

    # Source language (XXX hardcoded)
    source_language = 'en'

    # Target languages
    target_languages = [ x for x in languages if x != source_language ]

    # Build MO files
    print '(1) Compiling message catalogs:',
    sys.stdout.flush()
    for language in languages:
        print language,
        sys.stdout.flush()
        os.system('msgfmt locale/%s.po -o locale/%s.mo' % (language, language))
        # Add to the manifest
        manifest.append('locale/%s.mo' % language)
    print 'OK'

    # Load message catalogs
    message_catalogs = {}
    for language in languages:
        message_catalogs[language] = get_handler('locale/%s.po' % language)

    # Build the templates in the target languages
    print '(2) Building XHTML files',
    sys.stdout.flush()
    cmd = 'find -name "*.x*ml.en" | grep -v "^./build" | grep -v "^./dist"'
    for path in os.popen(cmd).readlines():
        # Load the handler
        path = path.strip()
        resource = get_resource(path)
        handler = XHTML.Document(resource)
        # Build the translation
        n = path.rfind('.')
        for language in target_languages:
            message_catalog = message_catalogs[language]
            target = '%s.%s' % (path[:n], language)
            open(target, 'w').write(handler.translate(message_catalog))
            # Add to the manifest
            manifest.append(target[2:])
        # Done
        sys.stdout.write('.')
        sys.stdout.flush()
    print ' OK'

    # Find out the version string
    manifest.append('version.txt')
    print '(3) Find out the version string',
    sys.stdout.flush()
    version = get_version()
    if version is None:
        print 'ERROR: Not a git repository'
    else:
        open('version.txt', 'w').write(version)
        print 'OK'

    # Build the manifest file
    print '(4) Building list of files to install',
    sys.stdout.flush()
    manifest.sort()
    open('MANIFEST', 'w').write('\n'.join(manifest))
    print 'OK'
