#!/usr/bin/env python

import gtk, gconf
import string, os, re

class MigrationTool:

    CONFIG_PATH = "/apps/gdesklets"
    main_win = None

    #migrate the settings
    def migrate(self):
        
        # set up gconf client
        self.__client = gconf.client_get_default()
        self.__client.add_dir(self.CONFIG_PATH, gconf.CLIENT_PRELOAD_RECURSIVE)

        # open the new output files
        home = os.getenv("HOME")
        d_cfile = open(home+"/.gdesklets/displays","w")
        p_cfile = open(home+"/.gdesklets/positions","w")

        # get the current default profile
        p = self.__client.get(self.CONFIG_PATH + "/profile")
        d_cfile.write(p.get_string() +"\n")
        
        # for each profile in /apps/gdesklets/profiles/, write display info to the "displays" file
        # also for each id encountered, write real-x and real-y to the "positions" file
        profiles = self.__client.all_dirs(self.CONFIG_PATH + "/profiles")

        for p in profiles:
            
            profile_name = p[len(self.CONFIG_PATH + "/profiles/"):]

            display_list = (self.__client.get(p + "/main/displays")).get_string()
            displays = display_list.split(",")

            for d in displays:

                 d_info = d.split("::")
                 x_pos = (self.__client.get(p +"/"+ d_info[0] + "_default_/real-x")).get_string() 
                 y_pos = (self.__client.get(p +"/"+ d_info[0] + "_default_/real-y")).get_string() 

                 # write the data that was in gconf to the new config files
                 d_cfile.write("id"+ d_info[0] +" "+ d_info[1] +" "+ profile_name +"\n")  
                 p_cfile.write("id"+ d_info[0] +" "+ x_pos +" "+ y_pos +"\n")

                 # check if settings exist for this display -if so, they have to be moved in gconf
                 plist = " ".join(self.__client.all_dirs(p))
                 pattern = re.compile(d_info[0]+'[A-Za-z]+')

                 for match in (pattern.findall(plist)):
                     # copy all the entries to new location
                     entries = self.__client.all_entries(p +"/"+ match)
                     for entry in entries:
                         key  = entry.get_key()
                         nkey = self.CONFIG_PATH + "/id" + match + "/" +  key[len(p+"/"+match)+1:] 
                         self.__client.set(nkey, entry.get_value())

        # we are done...
        self.show_finished_dialog() 
    
    # make sure the user knows the risks    
    def show_warning(self, widget):
        global main_win  
                                                                                                                          
        dialog = gtk.Dialog("Warning!",main_win,0,(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL, gtk.STOCK_OK,gtk.RESPONSE_OK))
                                                                                                                          
        hbox = gtk.HBox(gtk.FALSE, 8)
        hbox.set_border_width(8)
        dialog.vbox.pack_start(hbox, gtk.FALSE, gtk.FALSE, 0)
        stock = gtk.image_new_from_stock(gtk.STOCK_DIALOG_QUESTION,gtk.ICON_SIZE_DIALOG)
        hbox.pack_start(stock, gtk.FALSE, gtk.FALSE, 0)
        label = gtk.Label("This will overwrite any existing 0.30 settings!\nDo you wish to continue?")
        hbox.pack_start(label, gtk.FALSE, gtk.FALSE, 0)
                                                                                                                          
        dialog.show_all()
                                                                                                                          
        response = dialog.run()
                                                                                                                         
        if response == gtk.RESPONSE_OK:
            self.migrate()
                                                                                                                          
        dialog.destroy()

    # Display the "all done!" dialog and close the app
    def show_finished_dialog(self):
        global main_win  
                                                                                                                          
        dialog = gtk.Dialog("All Done!",main_win,0,(gtk.STOCK_OK,gtk.RESPONSE_OK))
                                                                                                                          
        hbox = gtk.HBox(gtk.FALSE, 8)
        hbox.set_border_width(8)
        dialog.vbox.pack_start(hbox, gtk.FALSE, gtk.FALSE, 0)
        stock = gtk.image_new_from_stock(gtk.STOCK_DIALOG_INFO,gtk.ICON_SIZE_DIALOG)
        hbox.pack_start(stock, gtk.FALSE, gtk.FALSE, 0)
        label = gtk.Label("Settings have been migrated succesfully")
        hbox.pack_start(label, gtk.FALSE, gtk.FALSE, 0)
                                                                                                                          
        dialog.show_all()
        dialog.run()
        dialog.destroy()
        gtk.main_quit()

    # Displays the main window...
    def __init__(self):
        global main_win  
 
        # set up the window
        main_win = gtk.Window(gtk.WINDOW_TOPLEVEL)
        main_win.set_title("gDesklets Config Migration Tool")
        main_win.connect("delete_event", gtk.mainquit)
        main_win.set_border_width(10)
       
        # layout stuff 
        self.hbox = gtk.HBox(gtk.FALSE, 5)
        self.vbox = gtk.VBox(gtk.FALSE, 5)
        main_win.add(self.hbox)
        self.hbox.pack_start(self.vbox, gtk.FALSE, gtk.FALSE, 0)

        # Add the explanation
        label = gtk.Label("This tool will safely migrate your settings "
                          "from old versions of gDesklets (0.26.x series), so that they "
                          "will work with versions from 0.30 onwards.")
        label.set_justify(gtk.JUSTIFY_LEFT)
        label.set_line_wrap(gtk.TRUE)
        self.vbox.pack_start(label, gtk.FALSE, gtk.FALSE, 0)

        # Add the buttons
        self.hbox2 = gtk.HBox(gtk.FALSE, 5)
        self.button1 = gtk.Button("Migrate!")
        self.button1.connect("clicked", self.show_warning)
        self.button2 = gtk.Button("Exit")
        self.button2.connect("clicked", gtk.mainquit)
        self.hbox2.pack_start(self.button2, gtk.TRUE, gtk.TRUE, 10)
        self.hbox2.pack_start(self.button1, gtk.TRUE, gtk.TRUE, 10)
        self.vbox.pack_start(self.hbox2, gtk.FALSE, gtk.FALSE, 5)

        # display everything...
        main_win.show_all ()

def main():

    gtk.main()

if __name__ == "__main__":

    ob1 = MigrationTool()
    main()

