#!/usr/bin/python
import pgdb, os, sys, time

# Initialize DB link
if len(sys.argv) < 6:
    sys.exit(sys.argv[0]+" <directory> <host> <user> <password> <database>")

if len(sys.argv) > 6:
    delay=int(sys.argv[6])
else:
    delay=30
if not os.path.exists(sys.argv[1]):
    sys.exit("The directory you specified doesn't exist")
os.chdir(sys.argv[1])
db=pgdb.connect(user=sys.argv[3],password=sys.argv[4],host=sys.argv[2],database=sys.argv[5])
cursor=db.cursor()
remove=False
def getNode(parent, pxeconfig):
    global remove
    # Get id and mac for all nodes with the specified parent
    cursor.execute("SELECT id,mac FROM nodes WHERE id_parent='"+parent+"' AND id!='0'")
    items=cursor.fetchall()
    for item in items:
        old_pxeconfig=pxeconfig
        id=str(item[0])
        if id == "-1" and parent == "0":
            remove=True
        elif id != "-1" and parent == "0":
            remove=False
        mac=str(item[1]).lower().replace(":","-")

        # Get the PXE parameter for the current node
        cursor.execute("SELECT attributes.value FROM attributes LEFT JOIN attributesdef ON attributesdef.id=attributes.attributesdef_id LEFT JOIN nodes ON nodes.id=attributes.nodes_id WHERE attributesdef.name='PXE_CONFIG' AND nodes.id='"+id+"';")
        pxe=cursor.fetchall()
        if len(pxe) == 1:
            # We have a PXE parameter specified for that node
            pxeconfig=pxe[0][0]

        # Check if it's a computer and not only a node
        if mac != "00-00-00-00-00-00"  and (os.path.islink("01-"+mac) or not os.path.exists("01-"+mac) ):
            # Check and create/delete/modify the symlinks
            if not (os.path.islink("01-"+mac) and os.path.realpath("01-"+mac) == os.getcwd()+"/"+pxeconfig):
                if os.path.islink("01-"+mac):
                    os.remove("01-"+mac)
                if not remove:
                    os.symlink(pxeconfig,"01-"+mac)
            elif remove:
                os.remove("01-"+mac)
        getNode(id,pxeconfig)
        pxeconfig=old_pxeconfig

def dbReconnect():
    global db, cursor
    try:
        db=pgdb.connect(user=sys.argv[3],password=sys.argv[4],host=sys.argv[2],database=sys.argv[5])
        cursor=db.cursor()
        return True
    except pgdb.InternalError:
        return False

try:
    while 1:
        try:
            cursor.execute("SELECT attributes.value FROM attributes LEFT JOIN attributesdef ON attributesdef.id=attributes.attributesdef_id LEFT JOIN nodes ON nodes.id=attributes.nodes_id WHERE attributesdef.name='PXE_CONFIG' AND nodes.id='0';")
            pxe=cursor.fetchall()
            root_pxeconfig="default"
            if len(pxe) == 1:
                root_pxeconfig=pxe[0][0]
            getNode('0',root_pxeconfig)
        except pgdb.DatabaseError:
            while not dbReconnect():
                time.sleep(5)
            pass
        time.sleep(delay)
except KeyboardInterrupt:
    sys.exit("Exitting")
