#!/usr/bin/env python

import os, warnings
with warnings.catch_warnings():
	warnings.simplefilter("ignore")
	from paramiko.config import SSHConfig

cfgdir = os.getenv("HOME")+"/.ssh"
cfgfile = cfgdir+"/config"

try:
	config_file = file(cfgfile)
except IOError:
	if not os.path.exists(cfgdir):
			os.makedirs(cfgdir,0700)
	f = open(cfgfile,'w')
	o = '# SSH config file, \'man ssh_config\' for more details.\n\n'
	o += '#Host example\n'
	o += '#    hostname example.com\n'
	o += '#    user joebloggs\n'
	f.write(o)
	f.close()
	os.chmod(cfgfile, 0600)
	config_file = file(cfgfile)
	config = SSHConfig()
	config.parse(config_file)
	hosts = config._config
else:
	config = SSHConfig()
	config.parse(config_file)
	hosts = config._config
	
print '<openbox_pipe_menu>\n'

if len(hosts) >= 2:
	for h in hosts[1:]:
		if h.has_key('host') and h.has_key('hostname'):
			user = ''
			if h.has_key('user'):
				user = '-l '+h['user']+ ' '
			port = ['','']
			if h.has_key('port'):
				port[0] = '-p '+h['port']+ ' '
				port[1] = ':'+h['port']
			print '<menu id="ssh-'+h['host']+'" label="'+h['host']+'">'
			print '    <item label="Start terminal session">'
			print '        <action name="Execute">'
			print '            <command>'
			print '                terminator --command=&quot;ssh '+user+port[0]+h['hostname']+'&quot;'
			print '            </command>'
			print '        </action>'
			print '    </item>\n'
			print '    <item label="Browse with Thunar">'
			print '        <action name="Execute">'
			print '            <command>'
			print '                thunar ssh://'+h['hostname']+port[1]
			print '            </command>'
			print '        </action>'
			print '    </item>\n'
			print '</menu>\n'
	print '<separator/>\n'

print '<item label="Edit ~/.ssh/config">'
print '    <action name="Execute">'
print '        <command>'
print '            geany ~/.ssh/config'
print '        </command>'
print '    </action>'
print '</item>\n'

print '</openbox_pipe_menu>'


