#coding:utf-8
import os
import sys
import time
import shutil
import sunhpc
import subprocess
class Command(sunhpc.commands.create.pxelinux.command):
    """
    Build the updates images 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-updates-*.rpm out directory. default: `pwd`/pxeboot
    </param>

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

    <example cmd='create pxelinux updates'>
        build an updates 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.updates  = os.path.join(self.prefix, 'share', 'isobuild', 'anaconda-updates')

        self.copyBoot()
        self.makeRpms()

        os.chdir(cwd)

    def copyBoot(self):
        """copy updates 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.updates)
        dst_updates = os.path.join(self.src_base, 'images', 'updates.img')
        if os.path.exists(dst_updates):
            os.remove(dst_updates)

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

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

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

        rpm_fullname = 'sunhpc-anaconda-updates-%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-updates')
        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"
