#!/usr/bin/python2
#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 MySQLdb
import re


def findghosts():
    ghostitems=[]
    try:
        f = urllib2.urlopen("http://localhost/xymon/hobbit-cgi/ghostlist.sh?SORT=name&MAXAGE=300&TEXT")
    except urllib2.HTTPError, e:
        if e.code != 200:
            print 'error find ghost list'
            sys.exit(1)
    else:
        ghostitems_full = f.readlines()
        f.close()
        #'''<h3><center>Failed to retrieve ghostlist from server</center></h3> #'''
        for i in ghostitems_full:
            if i.find("Failed to retrieve") >= 0  :
                print "exiting because xymon ghost list failed"
                print i
                sys.exit(1)
            if i.find('127.0.0') == -1 :
               ghostitems.append(i.strip())
               print "ghost host found: %s" %i.strip()
            else:
               continue
    #ghostitems = ['192.168.1.233\t\tfeste32', '192.168.1.127\t\tjams3']
    return ghostitems

def readbb():
    bblist = []
    strip_list = []
    try:
        infile = open('/home/xymon/etc/hosts.cfg', 'r')
        #infile = open('/tmp/old-bb', 'r')
    except(IOError), e:
        print "couldn't open hosts.cfg file"
        sys.exit(1)
    else:
        bblist = infile.readlines()
        for line in bblist:
            strip_list.append(line.strip())


    infile.close()
    return strip_list


def ghost_type(ghostlist):
    match_gdict={}
    #query db with ghostname
    db = MySQLdb.connect(host="localhost", user="mythtv", passwd="mythtv", db="mythconverg")
    # create a cursor
    cursor = db.cursor()
    for item in ghostlist:
        host = item.split()[1].strip()
        cursor.execute("select value,data  from settings where hostname=%s and value in ('HostSystemType');",(host))
        hostvalues=cursor.fetchall()
        #this is here in case the db fails
        if len(hostvalues) == 0:
            hostvalues = (('HostSystemType','unknown system'),)

        #should return something like this(('HostSystemType', 'Frontend_only'),)
        #hostvalues = (('HostSystemType', 'Frontend_only'),)
        if  len(hostvalues) == 1:
            #get current systemtype and make it all lowercase
            current_hostvalue = hostvalues[0][1].lower()
            try:
                value = match_gdict[current_hostvalue]
                value.append(item)
                match_gdict[current_hostvalue] = value
            except:
                match_gdict[current_hostvalue] = [item]


    #{'Frontend_only': ['feste32', 'feste3', 'feste33']}
    return match_gdict

def check_duplicate(host_list,server):
    server_no_space=re.sub(r'\s', '',server)
    for line in host_list:
        line_no_space=re.sub(r'\s', '',line)

        if line_no_space.find(server_no_space) > -1  :
            #print "server in hostlist"
            return True
        else:
            continue


    return False

def create_new_hosts(matched_gdict,host_list):
    #loop over key in gdict
    for key,value in matched_gdict.iteritems():
        groupline = "title %s" %key
        #print key
        if key == "unknown system":
            host_append_line = "%s #"
        else:
            host_append_line = "%s #func"

        if groupline in host_list:
            insert_index = host_list.index(groupline) + 1
            for server in value:
                if check_duplicate(host_list,server) == False :
                    #host_append_line = "%s #func" %(server)
                    host_list.insert(insert_index,host_append_line %server)
        else:
            host_list.append(groupline)
            for server in value:
                #host_append_line = "%s #func" %(server)
                host_list.append(host_append_line %server)


    outfile = open("/home/xymon/etc/hosts.cfg","w")
    #outfile = open("/tmp/new-bb","w")
    for i in host_list:
        outfile.write(i + '\n' )
        outfile.close
    return



def go():
    ghostlist = findghosts()
    #print ghostlist

    if len(ghostlist) == 0 :
        sys.exit()

    #match ghosts to system type
    matched_gdict = ghost_type(ghostlist)

    host_list = readbb()
    create_new_hosts(matched_gdict,host_list)

if __name__ == "__main__":
    go()
