""" ssh.py - deskbar plugin to open a quick ssh terminal

Installation:

Install http://boinkor.net/misc/ssh-to somewhere into your path and
chmod +x it. Recommended terminal: urxvt.

Drop this file into ~/.gnome2/deskbar-applet/handlers/, wait for
deskbar to pick up the change and select the plugin in the
preferences.

If you use screen(1) on any of your ssh target hosts, you may want to
use the following line in your .screenrc there:

  # Make shift-PgUp and shift-PgDn work like they do in xterm.  (Note that this
  # requires a/xterm to be configured to pass those keys through, and not try to
  # act on them itself.)
  bindkey "^[[5$" eval "copy" "stuff ^u"
  bindkey "^[[a" eval "copy" "stuff ^p"
  bindkey -m "^[[5$" stuff ^u
  bindkey -m "^[[6$" stuff ^d
  bindkey -m "^[[a" stuff ^p
  bindkey -m "^[[b" stuff ^n

and create a file named ~/.screen-hosts/$HOST (with $HOST=the name of
the host that has screen running). That will enable screen-internal
scrolling of terminal output with Shift-Pageup/down and Shift-Up/Down.

Copyright (c) 2006 Andreas Fuchs <asf@boinkor.net>, http://boinkor.net/

Licence:
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.  """

from gettext import gettext as _

import gobject
import re
import os
import os.path
from deskbar.Handler import Handler
from deskbar.Match import Match
import gtk, gtk.gdk

HANDLERS = {
        "SSHHandler" : {
                "name": _("SSH"),
                "description": _("Open SSH connection to host"),
        }
}

class SSHMatch (Match):
    def __init__ (self, backend, **args):
        Match.__init__(self, backend, **args)

    def action(self, text=None):
        gobject.spawn_async(["ssh-to", self.name], flags=gobject.SPAWN_SEARCH_PATH)

    def get_verb(self):
        return _("SSH to <b>%(name)s</b>")

    def get_category(self):
        return "actions"


class SSHHandler(Handler):
    def __init__(self):
        Handler.__init__(self, "gnome-mime-application-x-shellscript.png")
        self.ITEMS = []

    def initialize(self):
        f = open(os.path.expanduser("~/.ssh/known_hosts"), "r")
        for line in f.readlines():
            result = re.match('^([^|#][^,]+),', line)
            if result:
                self.ITEMS.append(result.group(1))
        f.close
        f = open(os.path.expanduser("~/.ssh/config"), "r")
        for line in f.readlines():
            result = re.match('^Host\s+(.+)\s*$', line)
            if result:
                self.ITEMS.append(result.group(1))
        f.close
        self.ITEMS.sort()
    

    def query(self, query):
        result=[]
        query=query.lower()
        found_equal=0
        match = re.match('^([a-z]+://)(.*)', query)
        if match:
            if match.group(1) != 'ssh://':
                return []
            else:
                query=match.group(2)
            
        for k in self.ITEMS:
            if k.find(query) != -1:
                result.append(SSHMatch(self, name=k))
            if k == query:
                found_equal=1
        if (found_equal == 0):
            result.append(SSHMatch(self, name=query))

        return result

# debug with:
#handler = SSHHandler()
#handler.initialize()
#handler.query('baker')
