#coding:utf-8

import os
import sunhpc
class Plugin(sunhpc.commands.Plugin):
    """Relocates home directories to location on file server and fixes autofs.share"""

    def run(self, args):
        """修复auto.home文件"""

        auto_users, pwd_users, new_users = [], [], []

        # 先读取autofs已经挂载的用户名称
        auto_home = '/etc/auto.home'
        if os.path.exists(auto_home):
            with open(auto_home, 'r') as f:
                for li in f.readlines():
                    auto_users.append(li.split()[0])

        # 去重排序
        auto_users = sorted(list(set(auto_users)))

        # 获取工作目录 /works/home
        default_dir = '/export/home/'

        # fix /etc/default/useradd command
        userhome = 'HOME=%s' % default_dir[:-1]
        useradd  = '/etc/default/useradd'
        if self.cmd.matchText(useradd, userhome):
            data = []
            with open(useradd, 'r') as fe:
                for line in fe:
                    if line.startswith('HOME='):
                        data.append(userhome)
                        continue

                    data.append(line.strip())
            
            with open(useradd, 'w') as f:
                f.write('\n'.join(data))

        # 读取/etc/passwd文件新用户.
        fe = open('/etc/passwd', 'r')
        for line in fe.readlines():

            l = line[:-1].split(':')
            if len(l) < 6: continue

            username = l[0]
            homedirs = l[5]

            # 提取工作目录等于'/export/home'
            if homedirs[:len(default_dir)] == default_dir:
                pwd_users.append(username)

            # 过滤掉uid < 1000用户并且用户不在auto_users列表中.
            # auto_users列表中用户不需要使用usermod命令再次切换
            if self.handler_uid(line) and username not in auto_users:
                auto_users.append(username)

        fe.close()

        # cluster.local
        # 获取控制节点的域名称
        hostname = self.db.getHostAttr('localhost', 'Info_HomeDirSrv')
        if not hostname:
            hostname = '%s.%s' % (self.db.getFrontendName(),
                self.db.getHostAttr('localhost', 'Kickstart_PrivateDNSDomain'))

        # 如果有自定义参数,则添加.
        options = self.db.getHostAttr('localhost', 'Info_HomeDirOptions')
        if options:
            options = '\t-' + options
        else:
            options = ""

        # 清空/etc/auto.home内容.
        #open(auto_home, 'w').close()

        # 修正用户主目录.
        for user in pwd_users:
            cmd = '/usr/sbin/usermod -d %s %s' % (os.path.join('/home', user), user)
            for line in os.popen(cmd).readlines():
                self.cmd.addText(line)

            # auto gen authorized_keys
            rootssh = os.path.join(default_dir, user, '.ssh')
            if not os.path.exists(rootssh):
                os.makedirs(rootssh)

            rootrsa = os.path.join(rootssh, 'id_rsa')
            if not os.path.exists(rootrsa):
                self.cmd.command('repair.users.authorized', [user])

        content = []
        # 合并autofs用户和passwd新用户添加到new_users中.
        new_users.extend(auto_users)
        new_users.extend(pwd_users)
        new_users = sorted(list(set(new_users)))
        for user in new_users:
            # 更新这个 auto.home 文件.
            # /export/home/dell
            new_user_dir = os.path.join(default_dir, user)

            # dell  cluster.local:/export/home/dell
            autofs_entry = '%s%s\t%s:%s\n' % (user, options, hostname, new_user_dir)
            content.append(autofs_entry)

        with open(auto_home, 'w') as f:
            f.write(''.join(content))

    def handler_uid(self, x):
        l = x.split(':')
        if int(l[2]) < 1000:
            return False
        if l[0] in self.avoid_uname():
            return False
        return True

    def avoid_uname(self):
        return ['nobody', 'nobody4', 'noaccess', 'nfsnobody']
