#coding:utf-8
import os
import sys
import time
import shutil
import sunhpc
import subprocess
class Command(sunhpc.commands.create.pxelinux.command):
    """
    Build the product 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 sunhpc-anaconda-product-*.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 product'>
        build an product images 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.product  = os.path.join(self.prefix, 'share', 'isobuild', 'anaconda-product')

        self.copyBoot()
        self.makeRpms()

        os.chdir(cwd)

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

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

        os.chdir(self.product)
        dst_product = os.path.join(self.src_base, 'images', 'product.img')
        if os.path.exists(dst_product):
            os.remove(dst_product)

        ret = self.shcmd('find . |cpio -c -o|xz -9 --format=xz > %s' % dst_product, code=True)

        if os.path.exists(dst_product):
            self.msg('\tGenerate complete product.img')
        else:
            self.msg('Failed: %s.' % ret, 'a')

    def makeRpms(self):
        # 制作sunhpc-anaconda-cdboot-*.rpm文件.

        rpm_fullname = 'sunhpc-anaconda-product-%s-%s.noarch.rpm' % (sunhpc.version, sunhpc.version_micro)
        dst_fullname = os.path.join(self.dst_base, rpm_fullname)
        if os.path.exists(dst_fullname):
            os.remove(dst_fullname)

        argsk = []
        argsk.append('arch=noarch')
        argsk.append('name=sunhpc-anaconda-product')
        argsk.append('source=%s' % self.src_base)
        argsk.append('prefix=/export/sunhpc/install/source')
        argsk.append('outdir=%s' % self.dst_base)
        self.command('create.rpm', argsk)

RollName = "base"
