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

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

    <param type='Path' name='outdir'>
    specify an sunhpc-anaconda-initrd-*.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 efiboot cdrom=/mnt/cdrom'>
        build an boot cdrom 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.checkCDROM()
        self.copyBoot()
        self.makeRpms()

        os.chdir(cwd)

    def copyBoot(self):
        """copy /mnt/cdrom efiboot to current pxeboot directory."""

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

        # create current/source/images dirs
        os.makedirs(os.path.join(self.src_base, 'images'))

        install  = os.path.join(self.src_base, 'images', 'efiboot.img')
        efiboot = self.shcmd('find %s -type f -name efiboot.img -print' % self.cdrom)['o'].strip()

        # copy /mnt/cdrom/LiveOS/efiboot.img to current/source/images/efiboot.img
        shutil.copyfile(efiboot, install)
        if os.path.exists(install):
            self.msg('\tCopying complete efiboot.img')
        
    def makeRpms(self):
        # 制作sunhpc-anaconda-cdboot-*.rpm文件.

        rpm_fullname = 'sunhpc-anaconda-efiboot-%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-efiboot')
        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 checkCDROM(self):
        """check cdrom"""

        if not len(os.listdir(self.cdrom)):
            self.msg('Must mount an valid linux cd to %s.' % self.cdrom, 'a')

        efiboot = subprocess.run('find %s -type f -name efiboot.img -print >/dev/null' % self.cdrom, shell=True)
        if efiboot.returncode:
            self.msg('Not found the efiboot file. %s' % efiboot, 'a')

        # 读取版本信息
        # 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"
