#coding:utf-8

import os
import sys
import socket
import sunhpc
class Command(sunhpc.commands.add.host.command):
    """
     Add Host security keys to Database

    <arg type='string' name='host'>
    Host name of machine
    </arg>

    <param type='Bool' name='force'>
    Force overwrite secure attribute to database, default: false
    </param>

    <example cmd='add host security compute-0-0'>
    Adds one host security keys to database.
    </example>

    <example cmd='add host security compute-0-0 force=1'>
    force overwrite security keys to database.
    </example>
    """
    def nodeup(self, host):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(0.2)
        try:
            sock.connect((host, 22))
            buf = sock.recv(64)
            sock.send(b'SSH-2.0-nodeup\r\n')
            buf = sock.recv(1024)
            sock.close()
        except:
            return 0
        return 1

    def run(self, params, args):
        (force, enc) = self.fillParams([('force', 'no'), ('enc', 'sha')])

        if not args:
            self.msg('must supply an host', 'a')

        force    = self.str2bool(force)
        frontend = self.db.getFrontendName()
        hostname = self.getHostnames(args)[0]

        if hostname == frontend:
            self.msg('not add frontend keys to database', 'a')

        content = []
        output  = self.shcmd('/usr/bin/ssh-keyscan %s' % hostname)['o']
        nodeid  = self.newdb.getNodeId(hostname)
        line    = output.split('\n')
        for i in line:
            r = i.split()
            if not r or len(r) != 3: 
                continue

            attr, value = r[1], ' '.join(r[1:])
            content.append((attr, enc, value, nodeid))

        if not content:
            self.msg('Unable to retrieve any content %s' % hostname, 'a')

        for a, e, v, n in content: 
            rows = self.db.search('select * from secnodes where attr="%s" and node="%s"' % (a, n))
            if rows and not force:
                self.msg('Attribute %s already exists.' % a, 'a')

            if force and rows:
                cmd = '''update secnodes set attr="%s", 
                    enc="%s", value="%s", node="%s" where 
                        attr="%s" and node="%s" ''' % (a, e, v, n, a, n)
            else:
                cmd = 'insert into secnodes values("%s", "%s", "%s", "%s") ' % (a, e, v, n)

            self.db.execute(cmd)



















