#!/usr/bin/python2.4

# Copyright (C) 2004-2005 Ross Burton <ross@burtonini.com>
#               2005 Canonical
#
# 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., 59 Temple
# Place, Suite 330, Boston, MA 02111-1307 USA

import sys
import os
import gdbm
import gconf
import errno

uri = None

class MimeSearchInfo:
    def approved(self, component, package):
        return (self._wl_components.has_key(component) or
            self._wl_packages.has_key(package))

    def retry_open(self):
        if uri:
            import gnomevfs
            gnomevfs.url_show(uri)

    def __init__(self, string, datadir, desktopdir, 
                 cachedir, duri=None):
        self.string = string

        # read the packages whitelist (from the files)
        dict = {}
        for d in (datadir, '/etc/gnome-app-install'):
            try: f = open(d+'/mime-whitelist-packages')
            except IOError, e:
                if e.errno == errno.ENOENT: continue
                raise
            for l in f:
                v = l.strip()
                if v.startswith('#'): continue
                dict[v] = True
        self._wl_packages = dict

        # read the component whitelist (from gconf)
        client = gconf.client_get_default()
        l = client.get_list("/apps/gnome-app-install"+
                            "/mime-whitelist-components",
                            gconf.VALUE_STRING)
        dict = {}
        for v in l: dict[v] = True
        self._wl_components = dict

        # look up our entry and bomb if not found
        db = gdbm.open(os.path.join(cachedir, "gai-mime-map.gdbm"), 'rfu')
        try: value = db[string]
        except KeyError: value = ''

        any = False
        for e in value.split():
            (component,package) = e.split('/',1)
            if self.approved(component,package): return
            any = True

        if uri:
            from gettext import gettext as _
            import gtk
            import AppInstall

            if any: (msg,abbrev) = (_(
"Cannot open %s:"
" No application suitable for automatic installation is available"
" for handling this kind of file."
            ) % duri,
_("Error: no suitable application"))
            else: (msg,abbrev) = (_(
"Cannot open %s: "
" No application is known for this kind of file."
                ) % duri,
_("Error: no application found"))
            dlg = gtk.MessageDialog(None, gtk.DIALOG_MODAL,
                gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, msg)
            dlg.set_title(abbrev)
            dlg.run()
            dlg.destroy()
            sys.exit(6)
        else:
            print >>sys.stderr, "not offering packages for "+string
            if any:
                print >>sys.stderr, "only unapproved: "+value
                sys.exit(5)
            else:
                print >>sys.stderr, "no entry in mime map"
                sys.exit(4)

if __name__ == "__main__":

    #datadir = "/tmp/xxx/share/gnome-app-install"	
    datadir = "/usr/share/gnome-app-install"
    desktopdir = "/usr/share/app-install"
    cachedir = "/var/cache/app-install"

    # I tried using optparse here but:
    #	$ time python -c 'import optparse'
    #	real    0m0.134s
    #	user    0m0.120s
    #	sys     0m0.012s
    def badusage():
        print >>sys.stderr, "gnome-app-install bad usage"
        sys.exit(127)

    if len(sys.argv)==1:
        msi = None
    elif sys.argv[1].startswith('--mime-type='):
        if len(sys.argv)==2: duri = None
        elif len(sys.argv)==3: uri = sys.argv[2]; duri = uri
        elif len(sys.argv)==4: (uri,duri) = sys.argv[2:]
        else: badusage()

        mime_type = sys.argv[1][12:]
        msi = MimeSearchInfo(mime_type, datadir, desktopdir, 
                             cachedir, duri)
    else: badusage()

# We have already bombed out if the quick test fails.  We do this
#  import only now so that quick tests are really quick.
from AppInstall.AppInstall import AppInstall

if __name__ == "__main__":
    app = AppInstall(datadir, desktopdir, cachedir,
                         sys.argv, mime_search=msi)
    app.run()
