#coding:utf-8
import os
import sys
import sunhpc
import subprocess
class command(sunhpc.commands.HostArgumentProcessor, sunhpc.commands.report.command):
    pass

class Command(command):
    """
    Report the host to known hosts (public keys) for  
    /etc/ssh/ssh_known_hosts

    <example cmd='report knownhosts'>
    Outputs lists of public IPs to be used for /etc/ssh/ssh_known_hosts
    </example>
    """
      
    def run(self, param, args):
        self.beginOutput()
        self.addOutput('localhost', '# Added by sunhpc report knownhosts  #')
        self.addOutput('localhost', '#        DO NOT MODIFY               #')
        self.addOutput('localhost', '# If you need to add entries use     #')
        self.addOutput('localhost', '# /etc/ssh/ssh_known_hosts.local     #')

        # grab per-node public keys
        allhosts = {}
        cmd = """SELECT n.name, s.value FROM nodes n INNER JOIN
             secnodes s ON s.node = n.id """
        self.db.execute(cmd)

        for (host,pubkey) in self.db.fetchall():
            ipaddr = self.newdb.getHostIp(host)
            #data = "%s,%s %s" % (host, ipaddr, pubkey.rstrip('\n'))
            allhosts[host] = [ipaddr, pubkey.rstrip('\n')]

        cmd = """SELECT n.name,s.dnszone,net.name,s.name FROM nodes n INNER JOIN
             networks net ON net.node = n.id INNER JOIN 
             subnets s on net.subnet = s.id; """
        self.db.execute(cmd)
        for (host,zone,ifname,subnet) in self.db.fetchall():
            if host in allhosts and zone is not None:
                if ifname is not None:
                    hostname = ifname 
                else:
                    hostname = host
                self.addOutput('localhost', 
                    '%s.%s,%s %s' % (hostname, zone, allhosts[host][0], allhosts[host][1]))
                if subnet == 'private':
                    self.addOutput('localhost', 
                     '%s,%s %s' % (hostname, allhosts[host][0], allhosts[host][1]))
                    
        cmd = """SELECT s.value FROM secglobals s 
            WHERE s.attr = 'ssh_host_rsa_key.pub'"""
        row = self.db.search(cmd)
        if row > 0: 
            pubkey, = self.db.fetchone()
        else:
            pubkey = None
        if pubkey is not None:
            pubkey = pubkey.rstrip('\n')

        cmd = """SELECT dnszone FROM subnets where dnszone 
                IS NOT NULL AND subnets.name != 'public';"""
        self.db.execute(cmd)
        for zone, in self.db.fetchall():
            if pubkey is not None:
                self.addOutput('localhost', 
                    '*.%s %s' % (zone,pubkey))

        cmd = """SELECT n.name,s.dnszone,net.name FROM nodes n INNER JOIN
             networks net ON net.node = n.id INNER JOIN 
             subnets s on net.subnet = s.id AND s.name = 'private'; """
        self.db.execute(cmd)

        if pubkey is not None:
            for (host,zone,ifname) in self.db.fetchall():
                if host not in allhosts:
                    if ifname is not None:
                        hostname = ifname 
                    else:
                        hostname = host
                    ipaddr = self.newdb.getHostIp(hostname)
                    self.addOutput('localhost',
                        '%s,%s %s' % (hostname, ipaddr, pubkey))

        hostlocal = '/etc/ssh/ssh_known_hosts.local'
        try:
            f = open(hostlocal,'r')
            self.addOutput('localhost','#\n# Imported from %s\n#' % hostlocal)
            h = f.read()
            self.addOutput('localhost',h)
            f.close()
        except :
            pass

        self.endOutput(padChar='')

RollName = "base"


RollName = "base"
