#!/usr/bin/python
#polls the hobbit server for ghost clients.  If it finds ghosts it will make a new bb-hosts file
#with the new clients.
#Will not add duplicate clients
#return code of 0 means a new file was written, anything else is an error or no inserts occured
import urllib2
import string
import sys
import os

def readkeyfile():
	global keylist
	try:
		infile = open('/data/home/mythtv/.ssh/authorized_keys', 'r')
	except(IOError), e:
           keylist=''
    	else:
    		keylist = infile.readlines()
		infile.close()


def grabkey(server):
	global numberlines
	global mbekey
	url="http://" + server + ":1337/serverkey.cgi"

	try:
		f = urllib2.urlopen(url)
	except urllib2.HTTPError, e:
		if e.code != 200:
			print 'error find key'
			sys.exit(1)
	else:
		mbekey = f.readlines()
		f.close()
        numberlines = len(mbekey)
        #print mbekey


def makenewkeyfile():
	global keylist
	global mbekey
	global numberlines
	global numinserts
	numinserts=0
	outlist = []
	for item in keylist:
		if item not in outlist:
			outlist.append(item)

	for item in mbekey:
#		line = item.rstrip()
		#nline = "%s #" % (line)
		#nline = nline + '\n'
		if item not in outlist:
			outlist.append(item)
			#print "adding: " + item
			numinserts = numinserts + 1
	if numinserts > 0:
		try:
			outfile = open("/data/home/mythtv/.ssh/authorized_keys","w")
		except(IOError), e:
        		os.system('mkdir -p /data/home/mythtv/.ssh') 
			outfile = open("/data/home/mythtv/.ssh/authorized_keys","w")
		for i in outlist:
			outfile.write(i + '\n' )
			outfile.close
			os.system('chown -R mythtv /data/home/mythtv/.ssh')
			os.system('chmod 700 /data/home/mythtv/.ssh/authorized_keys')
		

global infile
global keylist
global numberlines
global numinserts
global mbekey
numinserts = 0
readkeyfile()

#print numberlines
#print mbekey

try:
	infile = open('/etc/systemconfig', 'r')
except(IOError), e:
	sys.exit(1)
else:
    		keylist = infile.readlines()
		infile.close()
for  item in keylist:
	if item.startswith("dbhost"):
		itemlist=item.split("=")
		server=itemlist[1].strip()
		server=server.rstrip()
		server=server.strip('"')
		server=server.rstrip('"')
grabkey(server)


if numberlines > 0:
	makenewkeyfile()
else:
	print "nothing to add"


if numinserts < 1:
	sys.exit(1)
else:
	sys.exit(0)