#coding:utf-8

import os
import sys
import sunhpc
class Command(sunhpc.commands.add.command):
    """
    Add all secure attribute to the database.

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

    <example cmd='add security'>
    adds all secure attr to database
    </example>

    <example cmd='add security force=1'>
    force overwrite secure attr to database
    </example>
    """

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

        attr_list   = []
        force       = self.str2bool(force)

        # add /etc/ssh/*.pub to attr_list
        sshd_dirs = '/etc/safe-security'
        for i in os.listdir(sshd_dirs):
            try:
                if i.split('.')[-1] != 'pub':
                    continue
            except KeyError:
                pass

            with open(os.path.join(sshd_dirs, i), 'r') as fe:
                value = fe.read() 

            attr_list.append((i, value))

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

            if force and rows:
                cmd = 'update secglobals set attr="%s", value="%s", enc="%s" where attr="%s" ' % (n, v, enc, n)
            else:
                cmd = 'insert into secglobals values("%s", "%s", "%s") ' % (n, v, enc)
        
            self.db.execute(cmd)
        
RollName = 'base'












