## -*- coding: utf-8 -*-
#
# «services» - MCC Services enablement plugin
#
# Copyright (C) 2009, Mario Limonciello, for Mythbuntu
#
#
# Mythbuntu 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 application; if not, write to the Free Software Foundation, Inc., 51
# Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
##################################################################################

from MythbuntuControlCentre.plugin import MCCPlugin
from mythbuntu_common.dictionaries import get_services_dictionary
from mythbuntu_common.vnc import VNCHandler
import re
import shutil
import os
from gi.repository import Gtk

class MCCServices(MCCPlugin):
    """Services enablement plugin"""

    def __init__(self):
        information = {}
        information["name"] = "Services"
        information["icon"] = "gnome-settings"
        information["ui"] = "tab_services"
        MCCPlugin.__init__(self,information)
        self.vnc=VNCHandler()

    def captureState(self):
        """Determines the state of the items on managed by this plugin
           and stores it into the plugin's own internal structures"""
        #Most services meet this category
        self.dictionary_state={}
        list = get_services_dictionary(self)
        for item in list:
            if list[item] is not None:     
                self.dictionary_state[list[item]]=self.query_installed(item)

        #VNC password
        self.vnc_pass=''

    def applyStateToGUI(self):
        """Takes the current state information and sets the GUI
           for this plugin"""
        #from previous runs
        self.vnc_pass_hbox.hide()

        #Load the detected dictionary
        for item in self.dictionary_state:
            model = item.get_model()
            if len(model) > 2:
                iter = model.get_iter(Gtk.TreePath([2,0]))
                model.remove(iter)
            if self.dictionary_state[item]:
                item.set_active_iter(model.get_iter(Gtk.TreePath([1,0])))
                model.append(["Reconfigure"])
            else:
                item.set_active_iter(model.get_iter(Gtk.TreePath([0,0])))

        #Corner cases that don't need reconfiguring
        model = self.enablessh.get_model()
        if len(model) > 2:
            iter = model.get_iter(Gtk.TreePath([2,0]))
            model.remove(iter)


    def compareState(self):
        """Determines what items have been modified on this plugin"""
        #Prepare for state capturing
        MCCPlugin.clearParentState(self)

        list=get_services_dictionary(self)
        for item in list:
            if list[item] is not None and \
               list[item].get_active() != self.dictionary_state[list[item]]:
                #Installable items
                if list[item].get_active() == 1:
                    self._markInstall(item)
                #Removable items
                elif list[item].get_active() == 0:
                    self._markRemove(item)

                #Reconfigurable items:
                if list[item].get_active() > 0  and \
                   item != 'openssh-server'     and \
                   item != 'x11vnc':
                    self._markReconfigureRoot(item,list[item].get_active())

        #VNC password
        if self.vnc_pass != self.vnc_password.get_text():
            bytepassword = self.vnc_password.get_text().encode('utf-8')
            self._markReconfigureUser("x11vnc_password",bytepassword)

    def toggle_vnc(self,widget):
        """Called whenever VNC service is toggled"""
        if (widget is not None and widget.get_name() == 'enablevnc'):
            iteration=1
            if self.dictionary_state[self.enablevnc]:
                iteration = 2
            if widget.get_active() == iteration:
                self.vnc_pass_hbox.show()
                self.vnc_error_image.show()
                self._incomplete=True
            else:
                self.vnc_password.set_text("")
                self.vnc_pass_hbox.hide()
                self.vnc_error_image.hide()
                self._incomplete=False

    def toggle_vnc_password(self,widget):
        if (widget is not None and widget.get_name() == 'vnc_password'):
            password= widget.get_text().split(' ')[0]
            if len(password) >= 6:
                self.vnc_error_image.hide()
                self._incomplete=False
            else:
                self.vnc_error_image.show()
                self._incomplete=True

    def root_scripted_changes(self,reconfigure):
        """System-wide changes that need root access to be applied.
           This function is ran by the dbus backend"""
        for item in reconfigure:
            if item == "samba":
                if os.path.exists('/etc/samba/smb.conf'):
                    shutil.copy('/etc/samba/smb.conf','/etc/samba/smb.conf.dpkg-dist')
                shutil.copy('/usr/share/mythbuntu/examples/smb.conf.dist',
                            '/etc/samba/smb.conf')
            elif item == "nfs-kernel-server":
                if os.path.exists('/etc/exports'):
                    shutil.copy('/etc/exports','/etc/exports.dpkg-dist')
                shutil.copy('/usr/share/mythbuntu/examples/exports.dist',
                            '/etc/exports')

    def user_scripted_changes(self,reconfigure):
        """Local changes that can be performed by the user account.
           This function will be ran by the frontend"""
        for item in reconfigure:
            if item == "x11vnc_password":
                self.vnc.create_password(reconfigure[item])
