#!/usr/bin/env python
"""
LICENSE
=======
 
Copyright (c) 2014, Bram Van Steenlandt - bram at tivas.info
All rights reserved.
 
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
 
   * Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
   * Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.
   * Neither the name of the <ORGANIZATION> nor the names of its
     contributors may be used to endorse or promote products derived from
     this software without specific prior written permission.
 
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""
from __future__ import print_function, unicode_literals
from gi.repository import Gio, Gtk, GLib
from gi.overrides.GLib import Variant
import subprocess
import base64, os, signal, sys, time
 
def find_app(app):
    s = subprocess.Popen(["whereis", app],stdout=subprocess.PIPE)
    stdout, stderr = s.communicate()
    path = stdout.strip().split(":")[1]
    if path: return path
 
    print("Can't find vino-server !")
    sys.exit(1)
 
def is_running(process):
    s = subprocess.Popen(["pgrep", process], stdout=subprocess.PIPE)
    stdout, stderr = s.communicate()
    if stdout: return int(stdout)
    else: return False
 
VINO_SERVER_PATH = find_app("vino-server")
VINO_DESKTOP_FILE = """
[Desktop Entry]
Name=Remote Desktop
Comment=GNOME Remote Desktop Server
Exec=%s
Terminal=false
Type=Application
""" % VINO_SERVER_PATH            
 
class DialogInfo(Gtk.Dialog):

    def __init__(self, parent,info):
        Gtk.Dialog.__init__(self, "Vino info", parent, 0,(Gtk.STOCK_OK, Gtk.ResponseType.OK))


        label = Gtk.Label(info)

        box = self.get_content_area()
        box.add(label)
        self.set_position(Gtk.WindowPosition.CENTER)
        self.show_all() 
 
 
class App(Gtk.Window):
    BASE_KEY = "org.gnome.Vino"
    def __init__(self):
        Gtk.Window.__init__(self, title='Mate Vino Settings', border_width=24)
 
        # setup a check button and associate it with a GSettings key
        self.settings = Gio.Settings.new(self.BASE_KEY)
        if "enabled" in self.settings: self.vino_has_enabled = True
        else: self.vino_has_enabled = False
 
        self.btn_enabled = Gtk.CheckButton.new_with_mnemonic("_Enable Remote Access (VNC)")
        if self.vino_has_enabled:
            self.btn_enabled.param="enabled"
            self.btn_enabled.set_active(self.settings.get_boolean(self.btn_enabled.param))
            self.settings.connect("changed::%s"%(self.btn_enabled.param), self.on_my_setting_changed, self.btn_enabled)
        else:
            self.btn_enabled.set_active(is_running("vino-server"))
        self.btn_enabled.connect('toggled', self.on_enabled_button_toggled)
       
        self.btn_view = Gtk.CheckButton.new_with_mnemonic("_View only")
        self.settings.bind("view-only", self.btn_view, "active", Gio.SettingsBindFlags.DEFAULT)
       
        self.btn_ask = Gtk.CheckButton.new_with_mnemonic("_Ask user for access")
        self.settings.bind("prompt-enabled", self.btn_ask, "active", Gio.SettingsBindFlags.DEFAULT)
       
        # Auth, ask pasword ?
        self.btn_auth = Gtk.CheckButton.new_with_mnemonic("_Require a password")
        self.btn_auth.set_name("authentication-methods")
        val = self.settings.get_value(self.btn_auth.get_name())
        if 'vnc' in val:
            self.btn_auth.set_active(True)
        else:
            self.btn_auth.set_active(False)
        self.settings.connect("changed::%s" % self.btn_auth.get_name(), self.on_setting_auth_changed, self.btn_auth)
        self.btn_auth.connect('toggled', self.on_check_button_auth_toggled)
 
        # the password itself
        hsizer = Gtk.HBox()
        hsizer.props.spacing = 6
        hsizer.props.margin_left = 4
       

        self.field_pass = Gtk.Entry()
        self.field_pass.props.sensitive = self.btn_auth.get_active()
        self.field_pass.connect('key_release_event', self.on_field_pass_changed)
 
        self.on_passwd_changed(self.settings, "vnc-password")
        self.field_pass.set_visibility(False)
 
        hsizer.add(self.field_pass)
 
        self.settings.connect("changed::vnc-password", self.on_passwd_changed)
 
 
        # checkbox to show the password
        self.btn_pwshow = Gtk.CheckButton.new_with_mnemonic("Show _password")
        self.btn_pwshow.props.sensitive = self.btn_auth.get_active()
        self.btn_pwshow.set_active(False)
        self.btn_pwshow.connect('toggled', self.show_pw)
 
        # encryption, encryption type on centos is TLS which isn't very widely supported
        # recompiling vino may be better isn this case..
        #require-encryption
        self.btn_encryption = Gtk.CheckButton.new_with_mnemonic("_Encryption")
        self.settings.bind("require-encryption", self.btn_encryption, "active", Gio.SettingsBindFlags.DEFAULT)
       
        vsizer = Gtk.VBox()
        label = Gtk.Label.new_with_mnemonic('')
        label.set_markup('<b>Sharing</b>')
        vsizer.add(label)
        vsizer.add(self.btn_enabled)
        vsizer.add(self.btn_view)
        label = Gtk.Label.new_with_mnemonic('')
        label.set_markup('<b>Security</b>')
        vsizer.add(label)        
        vsizer.add(self.btn_ask)
        vsizer.add(self.btn_auth)
        vsizer.add(hsizer)
        vsizer.add(self.btn_pwshow)
        vsizer.add(self.btn_encryption)
       
        self.add(vsizer)
        self.update_btn_status()
       
    def show_pw(self, button):
        self.field_pass.set_visibility(button.get_active())
 
    def on_passwd_changed(self, settings, key):
        passwd = settings.get_string(key)
        if passwd == "keyring":
            # gnome keyring is used, warn the user
            self.field_pass.set_text("")
            dialog = DialogInfo(self,"Your password is set to keyring, this in unsupported, please enter a new password.")
            response = dialog.run() 
            dialog.destroy()
        else:
            self.field_pass.set_text(base64.b64decode(passwd))
 
    def on_field_pass_changed(self,a,b):
        self.settings.set_value("vnc-password", Variant('s',base64.b64encode(self.field_pass.get_text())))
   
    def on_setting_auth_changed(self, settings, key, check_button):
        val = settings.get_value(key)
        if 'vnc' in val:
            check_button.set_active(True)
        else:
            check_button.set_active(False)
 
    def on_check_button_auth_toggled(self, button):
        self.update_btn_status()
        if button.get_active():
            self.settings.set_value(button.get_name(), Variant('as',['vnc']))  
        else:
            self.settings.set_value(button.get_name(), Variant('as',['none']))
    def on_my_setting_changed(self, settings, key, check_button):
        check_button.set_active(settings.get_boolean(check_button.param))
        
    def on_enabled_button_toggled(self, button):
        if self.vino_has_enabled:
            self.settings.set_boolean(button.param, button.get_active())
        # If this is the "enabled" button:
        # Asume Gome settings daemon isn't running
        # check if the vino server is running, kill it if the user clicked the checkbox off, start it if the user clicked enable
        # also, make sure it autostarts next time we login
       
        enabled = button.get_active()
        running = is_running("vino-server")
        config_dir = GLib.get_user_config_dir()
        if not os.path.exists(config_dir):os.mkdir(config_dir)
        autostart_dir = "%s/autostart" % config_dir
        if not os.path.exists(autostart_dir):os.mkdir(autostart_dir)
        if enabled and not running:
            # start it
            print("**Starting vino-server**")
            time.sleep(0.1) # ? It takes a bit for the setting to be active ?
            subprocess.Popen(VINO_SERVER_PATH,shell=True)
            # Also check place an autostart file
            # these are located in .config/autostart
            f = file("%s/autostart/vino-server.desktop" % config_dir,"w")
            f.write(VINO_DESKTOP_FILE)
            f.close()
        elif not enabled:
            # remove autostart file
            if os.path.isfile("%s/autostart/vino-server.desktop" % config_dir):
                os.remove("%s/autostart/vino-server.desktop" % config_dir)
            # on newer installations, vino-server should be killed, older ones stop by itself
 
            if running and not self.vino_has_enabled:
                print("**Stopping vino-server**")
                os.kill(running,signal.SIGINT)
               
        self.update_btn_status()
        
    def update_btn_status(self):
        active = self.btn_enabled.get_active()
        active_pw = self.btn_auth.get_active()
        
        self.btn_ask.props.sensitive = active
        self.btn_view.props.sensitive = active
        self.btn_encryption.props.sensitive = active
        self.btn_auth.props.sensitive = active
        
        self.field_pass.props.sensitive = (active & active_pw)
        self.btn_pwshow.props.sensitive = (active & active_pw)
        
               
if __name__ == "__main__":
    app = App()
    app.set_position(Gtk.WindowPosition.CENTER)
    app.connect("delete-event", Gtk.main_quit)
 
    app.show_all()
    Gtk.main()

