import os
import sunhpc
class command(sunhpc.commands.HostArgumentProcessor,
        sunhpc.commands.report.command):
    pass

class Command(command):
    """
    Report the host to IP address mapping in the form suitable for
    /etc/hosts.

    <example cmd='report host'>
    Outputs data for /etc/hosts.
    </example>
    """
    def hostlocal(self, hostsFile):

        if os.path.isfile(hostsFile):
            print ('# import from %s' % hostsFile)
            with open(hostsFile, 'r') as f:
                for line in f.readlines():
                    print (line[:-1])

    def extranics(self):
        self.db.execute("""select networks.IP, networks.Name from
            networks,subnets where subnets.name != "private" and
            networks.subnet = subnets.id and
            networks.ip is not NULL order by networks.IP""")

        nodes=[]
        for row in self.db.fetchall():
            node = sunhpc.core.utils.Struct()
            node.address = row[0]
            node.name    = [row[1],]
            nodes.append(node)

        for node in nodes:
            if node.name[0] is not None:
                print ('%s\t%s' % (node.address, ' '.join(node.name)))

    def hostlines(self, subnet, netmask):

        ip      = sunhpc.core.ip.IPGenerator(subnet, netmask)
        domain  = self.db.getHostAttr('localhost', 'Kickstart_PrivateDNSDomain')
        self.db.execute("""select n.id, n.rack, n.rank from nodes n order by n.id""")

        nodes=[]
        for row in self.db.fetchall():
            node = sunhpc.core.utils.Struct()
            node.id      = row[0]
            node.rack    = row[1]
            node.rank    = row[2]
            node.warning = None

            self.db.execute("""select networks.name, networks.ip
                from networks, subnets where
                networks.node = %d and
                subnets.name = "private" and
                networks.subnet = subnets.id and
                (networks.device not like 'vlan%%' or
                networks.device is NULL)""" %
                (node.id))

            row = self.db.fetchone()
            if row == None:
                continue

            nodes.append(node)
            node.name    = [row[0],]
            node.address = row[1]

            if not node.address:
                node.address = ip.dec()

            name  = 'compute-%d-%d' % (node.rack, node.rank)

            # If there is no name in the database, use the
            # generated one.
            if not node.name[0]:
                node.name = [name,]
            
            if node.name[0] != name:
                node.warning = 'originally %s' % name

        # Append names from the Aliases table.
        for node in nodes:
            self.db.execute('select nodes.alias from nodes '
                     'where nodes.id = %d' % (node.id))
            for alias, in self.db.fetchall():
                node.name.append(alias)

        # Format the data
        for node in nodes:
            fqdn  = "%s.%s" % (node.name[0], domain)
            entry = '%s\t%s %s' % (node.address, fqdn,
                ' '.join(node.name))
            if node.warning:
                entry = entry + ' # ' + node.warning
            print (entry)

    def run(self, param, args):
        self.beginOutput()
        self.addOutput('localhost', '# Added by sunhpc report host #')
        self.addOutput('localhost', '#        DO NOT MODIFY        #')
        self.addOutput('localhost', '#  Add any modifications to   #')
        self.addOutput('localhost', '#    /etc/hosts.local file    #\n')
        self.addOutput('localhost','127.0.0.1\tlocalhost.localdomain\tlocalhost\n')

        self.db.execute('select dnszone from subnets where name="private"')
        localzone, = self.db.fetchone()

        cmd = 'select nt.ip, n.alias, s.dnszone, '   +\
            'coalesce(nt.name,n.name) '     +\
            'from networks nt, subnets s, nodes n ' +\
            'where nt.subnet=s.id and nt.ip!="NULL" '   +\
            'and nt.node=n.id order by nt.subnet, nt.name'
        self.db.execute(cmd)

        # <ip> <name>.<private_zone> <name> <alias> <alias>.<private_zone>
        # <ip> <name>.<zonename> <alias>.<zonename>
        for (ip, alias, zone, record) in self.db.fetchall():
            # Add <ip> <name>.<zonename>
            h = '%s\t%s.%s' % (ip, record, zone)

            # If it's the private zone
            if zone == localzone:
                # Add the <name> entry
                h = h + '\t' + record
                # and the <alias> entry
                if alias:
                    h = h + '\t' + alias
            # Finally add the <alias>.<zonename> entry
            if alias:
                h = h + '\t' + '%s.%s' % (alias, zone)
            self.addOutput('localhost', h)

        # Finally, add the hosts.local file to the list
        hostlocal = '/etc/hosts.local'
        if os.path.exists(hostlocal):
            f = open(hostlocal,'r')
            self.addOutput('localhost','\n# Imported from /etc/hosts.local\n')
            h = f.read()
            self.addOutput('localhost',h)
            f.close()
        
        self.endOutput(padChar='')

RollName = "base"
