#coding:utf-8
import os
import sys
import pwd
import shutil
import sunhpc
class Command(sunhpc.commands.repair.command):
    """
    Repair the Sunhpc distribution permission.

    <example cmd='repair permission'>
    Repair the Sunhpc distribution permission.
    </example>
    """
    def run(self, params, args):

        #
        # repair database permission.
        #
        dbpath = os.path.join(self.prefix, 'data')
        dbfile = os.path.join(self.prefix, 'data', 'sunhpcdb')
        self.chown('apache', 'apache', [dbpath, dbfile])
        self.chmod('700', [dbpath, dbfile])

        #
        # Repair cgi file permission
        #
        distro = self.command('report.distro').strip()
        ksdirs = os.path.join(distro, 'sbin')
        kslist = list(map(lambda x: os.path.join(ksdirs, x), os.listdir(ksdirs)))
        self.chmod('755', kslist)

        #
        # Repair pxelinux.cfg 
        #
        pxedir = self.db.getHostAttr('localhost', 'pxelinuxdir')
        pxecfg = os.path.join(pxedir, 'pxelinux.cfg')
        pxes   = list(map(lambda x: os.path.join(pxecfg, x), os.listdir(pxecfg)))
        result = pxes + [pxecfg]
        self.chown('root', 'apache', result)
        self.chmod('664', pxes)
        self.chmod('755', [pxecfg])


    def chown(self, user, group, path=[]):
        for p in path:
            shutil.chown(p, user, group)

    def chmod(self, perms, path=[]):
        """ perms is oct number, e,g. 0o644"""
        for p in path:
            os.system('/usr/bin/chmod %s %s' % (perms, p))

RollName = "base"
