# -*- coding: utf-8 -*-
#
# «vnc» - libmythbuntu class for adding/removing VNC from configuration
#
# This script:
# Copyright (C) 2007-2008, 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 3 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

import os
import sys
import shutil

#import xorgconfig
import xkit
from xkit import xutils

#Script Directory
SCRIPTDIR = '/usr/share/mythbuntu-common/scripts'

class VNCHandler:
    """Used to properly enable VNC in a target configuration"""

    def __init__(self,root=''):
        self.add_modules = ["vnc"]
        self.add_screen = [ ['SecurityTypes', 'VncAuth'], ['UserPasswdVerifier', 'VncAuth'], ['PasswordFile', '/root/.vnc/passwd']]
        self.root = root
        
        self.xorg_conf_path = '/etc/X11/xorg.conf'
        
        try:
            self.xorg_conf = xutils.XUtils(self.xorg_conf_path)
        except(IOError, xkit.xorgparser.ParseException):#if xorg.conf is missing or broken
            self.xorg_conf = xutils.XUtils()

    def create_password(self,password):
        home = os.environ['HOME']
        if not os.path.exists(home + "/.vnc"):
            os.mkdir(home + "/.vnc")
        elif os.path.exists(home + "/.vnc/passwd"):
            print("Copying ~/.vnc/passwd to ~/.vnc/passwd.old")
            shutil.copy(home + "/.vnc/passwd",home + "/.vnc/passwd.old")

        if not isinstance(password, bytes):
            raise ValueError('Password should be passed as bytes')
        passpadd = (password + b'\x00' * 8)[:8]
        strkey = bytes(d3des.vnckey)
        ekey = d3des.deskey(strkey, False)
        ctext = d3des.desfunc(passpadd, ekey)
        with open(home + "/.vnc/passwd", 'wb') as f:
            f.write(ctext)

    def toggle_xorg(self,enable):
        """Adds necessary lines for enabling VNC upon the next boot"""

        # backup the current xorg.conf
        open(os.path.join(self.root + self.xorg_conf_path + ".old"), "w").write(open(self.root + self.xorg_conf_path).read())
        
        
        #Revert any existing settings first
        have_modules = len(self.xorg_conf.globaldict["Module"]) > 0
        have_screens = len(self.xorg_conf.globaldict["Screen"]) > 0
              
        if have_modules:
            for m in self.add_modules:
                self.xorg_conf.removeOption("Module", "Load", value=m, position=0)
        
        if have_screens:
            for item in self.add_screen:
                self.xorg_conf.removeOption("Screen", item[0], position=0)
        

        #Now re-enable if we want to
        if enable:
            if self.add_modules:
                if not have_modules:
                    self.xorg_conf.makeSection("Module")
                for m in self.add_modules:
                    self.xorg_conf.addOption("Module", "Load", m, position=0)
            
            if not have_screens:
                self.xorg_conf.makeSection("Screen", identifier="Default Screen")
            for item in self.add_screen:
                self.xorg_conf.addOption("Screen", item[0], item[1], optiontype="Option", position=0)
        
        self.xorg_conf.writeFile(self.root + self.xorg_conf_path)
        
