#coding:utf-8
import os
import sys
import time
import shutil
import sunhpc
import subprocess
class Command(sunhpc.commands.create.pxelinux.command):
    """
    Build the sunhpc client rpms file for the cluster

    <param type='Path' name='basedir'>
    supply an unpack base dirs. default: current directorys.
    </param>

    <param type='Path' name='outdir'>
    specify an rpm out directory. default: `pwd`/pxeboot
    </param>

    <param type='String' name='version'>
    specify an gen rpm version. default: use sunhpc version
    </param>

    <example cmd='create pxelinux client'>
        build an sunhpc client rpms file
    </example>
    """
    def run(self, param, args):

        cwd = os.getcwd()
        (self.src_base, self.dst_base, version) = self.fillParams([
            ('basedir', os.path.join(cwd, 'source')),
            ('outdir', os.path.join(cwd, 'pxeboot')),
            ('version', sunhpc.version)])

        self.kickstart  = os.path.join(self.prefix, 'share', 'isobuild', 'anaconda-sunhpc')
        self.copyBoot()

        os.chdir(cwd)

    def copyBoot(self):
        """copy kickstart file to current source directory."""

        # create current/source/images dirs
        ksdir  = os.path.join(self.src_base, 'kickstart')
        if os.path.exists(ksdir):
            shutil.rmtree(ksdir)
        os.makedirs(ksdir)

        kslist = os.listdir(self.kickstart)
        for k in kslist:
            tmpdir = os.path.join(self.kickstart, k)
            os.chdir(tmpdir)

            if os.path.exists(self.src_base):
                shutil.rmtree(self.src_base)

            os.makedirs(self.src_base)
            ret = self.shcmd('find . -print|cpio -mpud %s' % self.src_base)

            fullname = '%s-%s-%s.noarch.rpm' % (k, sunhpc.version, sunhpc.version_micro)
            dst_rpms = self.makeRpms(k, fullname)

            if os.path.exists(dst_rpms):
                self.msg('\tGenerate complete - %s.' % k)
            else:
                self.msg('\tFailed: %s.' % ret, 'a')

    def makeRpms(self, name, fullname):
        # 制作roll-*-kickstart.rpm文件.

        dst_fullname = os.path.join(self.dst_base, fullname)
        if os.path.exists(dst_fullname):
            os.remove(dst_fullname)

        argsk = []
        argsk.append('arch=noarch')
        argsk.append('name=%s' % name)
        argsk.append('source=%s' % self.src_base)
        argsk.append('prefix=/opt/sunhpc')
        argsk.append('outdir=%s' % self.dst_base)
        self.command('create.rpm', argsk)
        return dst_fullname

RollName = "base"
