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

    <param type='Path' name='cdrom'>
    specify an cdrom directory. default: /mnt/cdrom
    </param>

    <param type='string' name='version'>
    initrd name contains the version. default: sunhpc version
    </param>

    <example cmd='create pxelinux vminitrd cdrom=/mnt/cdrom'>
        build an boot vmlinux and initrd file
    </example>
    """
    def run(self, param, args):

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

        self.printVersion()
        self.copyBoot()
        self.makeRpms()

        os.chdir(cwd)

    def copyBoot(self):
        """copy /mnt/cdrom initrd vmlinuz to current pxeboot 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)

        initrds = 'initrd-%s-%s' % (sunhpc.version, self.arch)
        vmlinuz = 'vmlinuz-%s-%s' % (sunhpc.version, self.arch)

        dst_initrds = os.path.join(self.src_base, 'images', initrds)
        dst_vmlinuz = os.path.join(self.src_base, 'images', vmlinuz)

        src_initrds = self.shcmd('find %s -type f -name initrd.img -print|head -n1' % self.cdrom)['o'].strip()
        src_vmlinuz = self.shcmd('find %s -type f -name vmlinuz -print|head -n1' % self.cdrom)['o'].strip()

        # copy initrd.img to current/source/images/initrd-7.0-x86_64
        # copy vmlinuz to current/source/images/vmlinuz-7.0-x86_64
        if os.path.exists(dst_initrds):
            os.remove(dst_initrds)
        shutil.copyfile(src_initrds, dst_initrds)
        if os.path.exists(dst_initrds):
            self.msg('\tCopying complete %s' % initrds)
        else:
            self.msg('Failed: %s' % dst_initrds, 'a')

        if os.path.exists(dst_vmlinuz):
            os.remove(dst_vmlinuz)
        shutil.copyfile(src_vmlinuz, dst_vmlinuz)
        if os.path.exists(dst_vmlinuz):
            self.msg('\tCopying complete %s' % vmlinuz)
        else:
            self.msg('Failed for %s.' % dst_vmlinuz, 'a')

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

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

    def printVersion(self):

        # 读取版本信息
        # timestamp, 7.6, x86_64
        info = ['unkonw', 'unkown', 'unkown']
        with open(os.path.join(self.cdrom, '.discinfo'), 'r') as f:
            line = f.readlines()
            if len(line) >= 3:
                info[0] = line[0].strip()
                info[1] = line[1].strip()
                info[2] = line[2].strip()

        name = 'unkown'
        with open(os.path.join(self.cdrom, '.treeinfo'), 'r') as f:
            for l in f.readlines():
                if l.find('family') == 0:
                    try:
                        name = l.split('=')[1].strip()
                    except KeyError:
                        pass

        if name not in ['CentOS', 'Sunhpc']:
            self.msg('The %s is not supported.' % name, 'a')

RollName = "base"
