#!/usr/bin/python

# Ubuntu Tweak - PyGTK based desktop configure tool
#
# Copyright (C) 2007-2008 TualatriX <tualatrix@gmail.com>
#
# Ubuntu Tweak 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.
#
# Ubuntu Tweak 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 Ubuntu Tweak; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA

import os
import subprocess
from subprocess import PIPE
import dbus
import dbus.service
import dbus.mainloop.glib
import gobject

#This class is modified from softwareproperty. Author: Michael Vogt <mvo@debian.org>
class AptAuth:
    def __init__(self):
        self.gpg = ["/usr/bin/gpg"]
        self.base_opt = self.gpg + ["--no-options", "--no-default-keyring",
                                    "--secret-keyring", "/etc/apt/secring.gpg",
                                    "--trustdb-name", "/etc/apt/trustdb.gpg",
                                    "--keyring", "/etc/apt/trusted.gpg"]
        self.list_opt = self.base_opt + ["--with-colons", "--batch",
                                         "--list-keys"]
        self.rm_opt = self.base_opt + ["--quiet", "--batch",
                                       "--delete-key", "--yes"]
        self.add_opt = self.base_opt + ["--quiet", "--batch",
                                        "--import"]
        
       
    def list(self):
        res = []
        #print self.list_opt
        p = subprocess.Popen(self.list_opt,stdout=PIPE).stdout
        for line in p.readlines():
            fields = line.split(":")
            if fields[0] == "pub":
                name = fields[9]
                res.append("%s %s\n%s" %((fields[4])[-8:],fields[5], _(name)))
        return res

    def add(self, filename):
        #print "request to add " + filename
        cmd = self.add_opt[:]
        cmd.append(filename)
        p = subprocess.Popen(cmd)
        return (p.wait() == 0)
        
    def update(self):
        cmd = ["/usr/bin/apt-key", "update"]
        p = subprocess.Popen(cmd)
        return (p.wait() == 0)

    def rm(self, key):
        #print "request to remove " + key
        cmd = self.rm_opt[:]
        cmd.append(key)
        p = subprocess.Popen(cmd)
        return (p.wait() == 0)
        
class Daemon(dbus.service.Object):
    INTERFACE = "com.ubuntu_tweak.daemon"
    liststate = None

    @dbus.service.method(INTERFACE,
                         in_signature='ssssb', out_signature='s')
    def set_entry(self, url, distro, comps, comment, enabled):
        import apt_pkg
        from aptsources.sourceslist import SourceEntry, SourcesList
        apt_pkg.init()
        list = SourcesList()
        self.liststate = "expire"
        if enabled:
            list.add('deb', url, distro, comps.split(' '), comment)
            list.save()
            return 'enabled'
        else:
            for entry in list:
                if url in entry.str():
                    entry.disabled = True

            list.save()
            return 'disabled'

    @dbus.service.method(INTERFACE,
                         in_signature='', out_signature='s')
    def get_list_state(self):
        if self.liststate:
            return self.liststate
        else:
            return "normal"

    @dbus.service.method(INTERFACE,
                         in_signature='', out_signature='s')
    def clean_apt_cache(self):
        os.system('apt-get clean')

        return 'done'
            
    @dbus.service.method(INTERFACE,
                         in_signature='s', out_signature='s')
    def delete_file(self, path):
        os.system('rm "%s"' % path)
        if os.path.exists(path):
            return 'error'
        else:
            return 'done'
            
    @dbus.service.method(INTERFACE,
                         in_signature='s', out_signature='')
    def set_list_state(self, state):
        self.liststate = state

    @dbus.service.method(INTERFACE,
                         in_signature='ss', out_signature='')
    def edit_file(self, path, content):
        file = open(path, 'w')
        file.write(content)
        file.close()

    @dbus.service.method(INTERFACE,
                         in_signature='s', out_signature='s')
    def clean_config(self, pkg):
        return str(os.system('sudo dpkg --purge %s' % pkg))

    @dbus.service.method(INTERFACE,
                         in_signature='s', out_signature='')
    def add_apt_key(self, filename):
        apt_key = AptAuth()
        apt_key.add(filename)

    @dbus.service.method(INTERFACE,
                         in_signature='ss', out_signature='')
    def save_to_disk(self, text, filename):
        f = file(filename, 'w')
        f.write(text)
        f.close()

    @dbus.service.method(INTERFACE,
                         in_signature='', out_signature='')
    def exit(self):
        mainloop.quit()

if __name__ == '__main__':
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

    system_bus = dbus.SystemBus()
    name = dbus.service.BusName("com.ubuntu_tweak.daemon", system_bus)
    object = Daemon(system_bus, '/com/ubuntu_tweak/daemon')

    mainloop = gobject.MainLoop()
    mainloop.run()
