#!/usr/bin/python

# Author: Paul Wise <pabs@debian.org>
# License: MIT/Expat

import os
import sys
import ldap

def fail():
	print >>sys.stderr, 'Your ~/.ssh/config needs to contain these lines in this order:'
	print >>sys.stderr, start_str
	print >>sys.stderr, 'stuff to replace'
	print >>sys.stderr, end_str
	f.close()
	sys.exit(1)

start_str = '# Start of Debian porterbox aliases, do not touch'
end_str = '# End of Debian porterbox aliases, do not touch'
aliases = []

l = ldap.initialize('ldaps://db.debian.org')
r = l.search_s('ou=hosts,dc=debian,dc=org',ldap.SCOPE_SUBTREE,'(purpose=porterbox)',['architecture','access','host','hostname'])
for dn,e in r:
	aliases.append('# http://db.debian.org/machines.cgi?host=%s' % e['host'][0])
	aliases.append('Host %s %s.port %s.port.debian.org' % ((e['architecture'][0],)*3))
	aliases.append(' HostKeyAlias %s' % e['hostname'][0])
	aliases.append(' HostName %s' % e['hostname'][0])
del l, r

f = open(os.path.expanduser('~/.ssh/config'), 'r+b')
config = f.read().splitlines()
try:
	start = config.index(start_str) + 1
	end = config.index(end_str)
except:	fail()
if start >= 0 and end >= start:
	config[start:end] = aliases
else: fail()
f.seek(0)
f.write('\n'.join(config))
f.close()
