#coding:utf-8
import os
import sys
import sunhpc
class command(sunhpc.commands.repair.users.command):
    pass
class Command(command):
    """
    Repair the system users.
    <arg type='string' name='user'>
    Provide an user accecc name.
    </arg>

    <param type='Bool' name='all'>
    fix all users authorized_keys
    </param>

    <example cmd='repair users'>
    Repair user account information.
    </example>
    """
    def run(self, params, args):

        (alls, ) = self.fillParams([('all', 'no')])
        alls = self.str2bool(alls)

        if not args and not alls:
            self.msg('must supply an user or all=True', 'a')

        userlist = []
        
        if alls:
            userlist.extend(self.getAllUsers())

        if args:
            userlist.extend(args)

        # 去重.
        userlist = sorted(list(set(userlist)))

        home = '/export/home'
        for user in userlist:
            userhome = os.path.join(home, user)
            sshdhome = os.path.join(userhome, '.ssh')
            if not os.path.exists(sshdhome):
                os.makedirs(sshdhome)

            ssh_auth = os.path.join(sshdhome, 'authorized_keys')
            ssh_keys = os.path.join(sshdhome, 'id_rsa')
            ssh_pubs = os.path.join(sshdhome, 'id_rsa.pub')
                
            # create the id_rsa keypair
            if os.path.exists(ssh_keys):
                os.remove(ssh_keys)
                os.remove(ssh_pubs)
            cmd = '/usr/bin/ssh-keygen -q -t rsa -P "" -f %s' % ssh_keys
            os.system(cmd)

            # generate the authorized_keys
            if os.path.exists(ssh_pubs):
                cmd = '/usr/bin/cat %s > %s' % (ssh_pubs, ssh_auth)
                os.system(cmd)

            # chown and chmod ssh file
            os.system('chown -R %s:%s %s' % (user, user, userhome))
            
            os.chmod(userhome, 0o700)
            os.chmod(sshdhome, 0o700)
            os.chmod(ssh_auth, 0o644)
            os.chmod(ssh_keys, 0o600)
            os.chmod(ssh_pubs, 0o644)

    def getAllUsers(self):
        users  = []
        autofs = '/etc/auto.home'
        with open(autofs, 'r') as f:
            for line in f:
                users.append(line.split()[0])

        return users
        
RollName = "base"
