#!/usr/bin/python

# Copyright (C) 2009 Canonical Ltd.
#
# Author: Martin Pitt <martin.pitt@ubuntu.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., 675 Mass Ave, Cambridge, MA 02139, USA.
#

import sys
import locale
import os
import os.path

try:
    from xdg.DesktopEntry import DesktopEntry
    from xdg.Exceptions import ParsingError
except ImportError:
    print >> sys.stderr, 'ERROR: Cannot import gmenu, is a package upgrade in progress?'
    sys.exit(1)

# those are the fields which we need in the cache for presenting a menu
# taken from gnome-menus libmenu/desktop-entries.c,
# desktop_entry_load_from_keyfile()
fields = ['Name', 'GenericName', 'X-GNOME-FullName', 'Comment', 'Icon',
        'Exec', 'TryExec', 'Terminal', 'Type', 'Categories',
        'NoDisplay', 'OnlyShowIn', 'Hidden']

#
# main
#

def process_file(path, basedir):
    try:
        de = DesktopEntry(path)
    except ParsingError, e:
        print >> sys.stderr, 'Invalid desktop file %s: %s' % (path, str(e))
        return

    assert path.startswith(basedir)
    path = path[len(basedir):]
    if path.startswith('/'):
        path = path[1:]

    print '[%s]' % os.path.splitext(path)[0]
    for f in fields:
        val = None
        try:
            # fields which need translation
            if f in ['Name', 'GenericName', 'Comment']:
                val = getattr(de, 'get' + f)()
            elif f == 'X-GNOME-FullName':
                val = de.get(f, locale=True)
        except:
            pass

        if not val:
            val = de.get(f)

        if val:
            if type(val) == type([]):
                val = ';'.join(val)
            if type(val) == type(u''):
                val = val.encode('UTF-8')
            print '%s=%s' % (f, val)
    print

try:
    try:
        # we want the actual locale; a differing $LANGUAGE is taken care of in
        # the actual patch
        del os.environ['LANGUAGE']
    except KeyError:
        pass
    locale.setlocale(locale.LC_ALL, '')
except:
    print >> sys.stderr, 'WARNING: System locale is invalid'
    sys.exit(0)

if len (sys.argv) != 2:
    print >> sys.stderr, 'Usage: %s <desktop directory>' % sys.argv[0]
    sys.exit(0)

for (root, dirs, files) in os.walk(sys.argv[1]):
    for f in files:
        if f.endswith('.desktop'):
            process_file(os.path.join(root, f), sys.argv[1])
