#!/usr/bin/python2
# -*- coding: utf-8 -*-
# import MySQL module
import MySQLdb
import sys
import getopt
import socket
import os
def create_dot_file():
    try:
        import  ignoreclient
        ignorehostlist=ignoreclient.ignorehosts
    except:
        print "could not find the ignore list"
        ignorehostlist="'ignoreme'"
    db = MySQLdb.connect(host="localhost", user="mythtv", passwd="mythtv", db="mythconverg")
    cursor = db.cursor()
    SQL="SELECT DISTINCT(hostname) from settings where hostname not in(%s)"
    cursor.execute(SQL %ignorehostlist)
    result = cursor.fetchall()
    frontonly="_FRONTEND_"
    masterbackend="_MASTERBACKEND_"
    masterbacked_w_fe="_MASTERFRONTEND_"
    slave_w_fe="_SLAVEFE_"
    slave="_SLAVEBACKEND_"
    stand_alone="_STANDALONE_"
    dotMBE=""
    dotfrontend=list()
    dotslave=list()
    dotslavefe=list()
    tunerdict = {}
    for row in result:
       hostname = row[0]
       dot_hostname = row[0].replace('.','_')
       dot_hostname = row[0].replace('-','__')
       #Find the system type
       cursor.execute("select value,data  from settings where hostname=%s and value in ('HostSystemType','HostRunFrontend');",(row))
       hostvalues=cursor.fetchall()
       if  len(hostvalues) == 2:
          if hostvalues[1][1] == 'Frontend_only':
             frontonly+=","+dot_hostname
             dotfrontend.append(dot_hostname)
          elif hostvalues[1][1] == 'Standalone':
             stand_alone+=","+dot_hostname
             dotMBE="MBE" + " [ label=\"" + dot_hostname  + "  \\n Standalone  \" shapefile=\"/data/srv/httpd/htdocs/xymon/gifs/be.png\"  fontcolor=\"white\"  color=blue4 style=filled   ] "
             dotfrontend.append(dot_hostname)
             cursor.execute("select cardtype,defaultinput  from capturecard  where hostname=%s;",(row))
             tuners=cursor.fetchall()
             tstring=""
             if len(tuners) == 0:
                 tunerdict["MBE"]="no tuners \\n"
             else:
                for t in tuners:
                    tstring+=t[0]
                    tstring+=t[1]
                    tstring+='\\n'
                    tunerdict["MBE"]=tstring
          elif hostvalues[1][1] == 'Master_backend':
              if hostvalues[0][1]=='0':
                  masterbackend+=","+dot_hostname
                  dotMBE="MBE" + " [ label=\"" + dot_hostname  + "  \\n Master Backend \" shapefile=\"/data/srv/httpd/htdocs/xymon/gifs/be.png\"  fontcolor=\"white\"  color=blue4 style=filled   ] "
              else:
                  masterbacked_w_fe+=","+dot_hostname
                  dotMBE="MBE" + " [ label=\"" + dot_hostname  + "  \\n Master Backend with frontend  \" shapefile=\"/data/srv/httpd/htdocs/xymon/gifs/be.png\"  fontcolor=\"white\"  color=blue4 style=filled   ] "
                  dotfrontend.append(dot_hostname)
              cursor.execute("select cardtype,defaultinput  from capturecard  where hostname=%s;",(row))
              tuners=cursor.fetchall()
              tstring=""
              if len(tuners) <= 0:
                tunerdict["MBE"]="no tuners \\n"
              else:
                #print tuners
                for t in tuners:
                        tstring+=t[0]
                        tstring+=t[1]
                        tstring+='\\n'
                        tunerdict["MBE"]=tstring
          elif hostvalues[1][1] == 'Slave_backend':
              cursor.execute("select cardtype,defaultinput  from capturecard  where hostname=%s;",(row))
              tuners=cursor.fetchall()
              #slave withoutfe
              if hostvalues[0][1]=='0':
                  slave+=","+dot_hostname
                  dotslave.append(dot_hostname)
                  tstring=""
                  if len(tuners) <= 0:
                      tunerdict["STUNER"+dot_hostname]="No Tuners"
                  else:
                      for t in tuners:
                            tstring+=t[0]
                            tstring+=t[1]
                            tstring+='\\n'
                            tunerdict["STUNER"+dot_hostname]=tstring
              else:
                  #slave with fe
                  tstring=""
                  if len(tuners) <= 0:
                     tunerdict["STUNER"+dot_hostname]="No Tuners"
                  else:
                      for t in tuners:
                            tstring+=t[0]
                            tstring+=t[1]
                            tstring+='\\n'
                            tunerdict["STUNER"+dot_hostname]=tstring
                  slave_w_fe+=","+dot_hostname
                  dotslave.append(dot_hostname)
                  dotfrontend.append(dot_hostname)
#----------------------------------Create graphviz dot files
    dotfilename="/home/xymon/server/etc/mythdot"
    try:
        dotfile=open(dotfilename,'w')
        dotfile.write("digraph G {   " + "\n" )
        dotfile.write("graph [bgcolor=transparent]" + "\n" )
        #print tunerdict
        #define the nodes
        dotfile.write( dotMBE + "  \n" )
        dotfile.write("tunermbe"+   " [ label= \"" + tunerdict["MBE"] +     "\" , shapefile=\"/data/srv/httpd/htdocs/xymon/gifs/tuner.png\"   fontcolor=\"white\"  color=red ]  \n" )
        for fe in dotfrontend:
            dotfile.write("FEND"+fe + "[ label=\"frontend \\n " + fe +     "\" ,shapefile=\"/data/srv/httpd/htdocs/xymon/gifs/tv.png\" , fontcolor=\"white\" , imagescale=\"true\"  color=\"gold2\" ]   \n" )
        for fe in dotslave:
            cslave="STUNER"+fe
            #adding tuners to dot file
            if tunerdict[cslave] != "" :
                dotfile.write(cslave+   " [ label= \"" + tunerdict[cslave] +     "\" , shapefile=\"/data/srv/httpd/htdocs/xymon/gifs/tuner.png\"   fontcolor=\"white\"  color=red ]  \n" )
            #adding slave to dot file
            dotfile.write("SLAVE"+fe + "[ label=\"slave backend \\n " + fe +     "\" shapefile=\"/data/srv/httpd/htdocs/xymon/gifs/be.png\"  fontcolor=\"white\"  color=green ]   \n" )
        #connect up the nodes!
        dotfile.write("tunermbe -> MBE  [color=\"red\"] \n  "  )
        for fe in dotfrontend:
            dotfile.write("MBE  -> FEND" + fe + "[color=\"gold2\"]   \n  "  )
        for fe in dotslave:
            cslave="STUNER"+fe
            dotfile.write("SLAVE" + fe + "-> MBE [color=\"green\"]  \n  "  )
            if tunerdict[cslave] != "" :
                dotfile.write(cslave + "-> SLAVE"+fe +  "[color=\"red\"]"  "\n"  )
        dotfile.write("}  " + "\n"   )
        dotfile.close()
    except:
        print "Problem writing %s" %dotfilename
    cmd="/usr/bin/unflatten -l1 -c3 -f " + dotfilename + " |/usr/bin/dot -Tpng  -o/data/srv/httpd/htdocs/xymon/gifs/network.png "
 #   cmd="/usr/bin/circo -Tpng  -o/data/srv/httpd/htdocs/xymon/gifs/network.png " + dotfilename
    results=os.popen(cmd,'r')
    return frontonly,masterbackend,masterbacked_w_fe,slave_w_fe,slave,stand_alone
def createdropdown(currenthostype):
    dir = "/data/storage/disk0/backup/system_backups"
    dropdown='''
    
     Restore Database: >
     
          
    Partial Restore
    
    Upload File to Restore: >
    
    
    Backup System
    '''
    #This is for the d/l backup option
    dropdown+='''
    
    Download Backup: >
    
    
    
    Optimize Database
    '''
    if currenthostype == "Master_backend":
        dropdown+='Shutdown All Systems (except master backend)
 \n'
    #Add option to restart MBE
    dropdown+=' Restart MBE service
 \n'
    dropdown+='''    \n'''
    return dropdown
def create_notes():
    db = MySQLdb.connect(host="localhost", user="mythtv", passwd="mythtv", db="mythconverg")
    # create a cursor
    cursor = db.cursor()
    cursor.execute("SELECT DISTINCT(hostname) from settings")
    result = cursor.fetchall()
    for row in result:
       #cursor.execute("select value,data  from settings where hostname=%s and value in ('HostSystemType','HostHwuuid');",(row))
       cursor.execute("select value,data  from settings where hostname=%s and value in ('HostSystemType','HardwareProfilePublicUUID');",(row))
       hostvalues=cursor.fetchall()
       #This is here to ignore non LinHES hosts, or those that don't have a HostSystemType
       if len(hostvalues) == 0:
           continue
       found_uuid="false"
       filename="/home/xymon/server/www/notes/"
       filename+=str(row[0])
       filename+=(".html")
       try:
            file = open(filename,'w')
       except:
            print "problem opening %s" %filename
            continue
       string='''