#coding:utf-8
import time
import sunhpc
class Modules(object):
    """
    Configure sunhpc cluster security.
    """ 
    def __init__(self, command):
        self.cmd = command

    @property
    def __help__(self):
        info = """
        #==============================================================
        # %s
        #
        # module_path: %s
        # module_name: %s
        #==============================================================
        """ % (self.__doc__.strip(), self.__module__.strip(), self.__repr__())
        return info
        
    def run(self, args):

        content = [self.__help__]

        # master.pub and shared.key
        try:
            nodeid = self.cmd.newdb.getNodeId(args)
        except:
            nodeid = None

        if nodeid:
            mkeys = '/etc/safe-security/master.pub'
            skeys = '/etc/safe-security/shared.key'
            with open(mkeys, 'r') as f: mtext = f.read()
            with open(skeys, 'r') as f: stext = f.read()

            content.append(
                self.cmd.ks.makefile(
                    mtext, mkeys, perms="444", owner="root:root"))
            content.append(
                self.cmd.ks.makefile(
                    stext, skeys, perms="400", owner="root:root"))

        # ssh config not autogen ssh keys
        # check /usr/sbin/sshd-keygen
        sshd_file = "/etc/sysconfig/sshd"
        sshconfig = """
        # Configuration file for the sshd service.

        # The server keys are automatically generated if they are missing.
        # To change the automatic creation uncomment and change the appropriate
        # line. Accepted key types are: DSA RSA ECDSA ED25519.
        # The default is "RSA ECDSA ED25519"

        AUTOCREATE_SERVER_KEYS="NO"
        # AUTOCREATE_SERVER_KEYS="RSA ECDSA ED25519"

        # Do not change this option unless you have hardware random
        # generator and you REALLY know what you are doing

        SSH_USE_STRONG_RNG=0
        # SSH_USE_STRONG_RNG=1
        """
        content.append(self.cmd.ks.makefile(sshconfig, sshd_file, perms="640", owner="root.root"))

        # /etc/safe.conf
        address   = self.cmd.db.getHostAttr('localhost', 'Kickstart_PrivateAddress')
        safeport  = self.cmd.db.getHostAttr('localhost', 'safeport')
        safedirs  = self.cmd.db.getHostAttr('localhost', 'safedirs')
        safe_file = '/etc/safe.conf'
        safe_conf = """
        <!-- Safe security configuration -->
        <config>
            <url>http://%s</url>
            <port>%s</port>
            <urldir>%s</urldir>
        </config>
        """ % (address, safeport, safedirs)
        content.append(self.cmd.ks.makefile(safe_conf, safe_file, perms="644", owner="root.root"))

        # safeGet
        safe_info = """
        if [ -f /opt/sunhpc/sbin/safeGet ];then
            /opt/sunhpc/sbin/safeGet --all
        else
            echo "Error safeGet command not found." >> /tmp/sunhpc.log
        fi

        /usr/bin/chown root:ssh_keys /etc/ssh/ssh_host_ecdsa_key
        /usr/bin/chown root:ssh_keys /etc/ssh/ssh_host_ed25519_key
        /usr/bin/chown root:ssh_keys /etc/ssh/ssh_host_rsa_key
        """
        content.append(safe_info)

        ssh_config = '/etc/ssh/ssh_config'
        ssh_info   = """
        Host *
                CheckHostIP             no
                ForwardX11              yes
                ForwardAgent            yes
                StrictHostKeyChecking   no
                UsePrivilegedPort       no
                Protocol                2,1
                HostbasedAuthentication yes
                EnableSSHKeySign        yes
        """
        content.append(self.cmd.ks.makefile(ssh_info, ssh_config, perms="644", owner="root.root"))

        sshd_info = """
        echo "MaxStartups 1280" >> /etc/ssh/sshd_config
        echo "Match User root" >> /etc/ssh/sshd_config
        echo "      HostbasedAuthentication no" >> /etc/ssh/sshd_config
        """
        content.append(sshd_info)

        # memory sysctl
        mem_info = """
        SHMSIZE=`gawk '/MemTotal:/ { printf("(%s/4) * (3 * 1024)\\n", $2); }' /proc/meminfo | bc`
        if [ $SHMSIZE ]
        then
            echo "kernel.shmmax = " $SHMSIZE >> /etc/sysctl.conf
        fi

        """
        content.append(mem_info)

        self.cmd.ks.addPost(content)
    def __repr__(self):
        return "kickstart-security"
















