# -*- coding: utf-8 -*-

# Copyright 2015-2016 Mir Calculate. http://www.calculate-linux.org
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import sys
import re
from os import path
from files import typeFile, process
from subprocess import Popen, PIPE
from calculate.lib.cl_lang import setLocalTranslate

setLocalTranslate('cl_lib3', sys.modules[__name__])

class InitrdFileError(Exception):
    pass

class InitrdFile(object):
    """
    Работа с initrd файлом
    """
    re_kver_path = re.compile("/modules/([^/]+)/kernel")

    def __init__(self, _file):
        if not self.is_cpio(_file):
            raise InitrdFileError("%s is not initrd file" % _file)
        self._file = _file

    def get_kernel_version(self):
        for fn in self.get_names():
            if "/modules/" in fn and "/kernel" in fn:
                m = self.re_kver_path.search(fn)
                if m:
                    return m.group(1)
                else:
                    break
        return ""

    @staticmethod
    def skipcpio_data(fn):
        skipcpio_cmd = "/usr/lib/dracut/skipcpio"
        skipcpio = Popen([skipcpio_cmd, fn], stdout=PIPE, stderr=PIPE,
                   close_fds=True)
        buf = skipcpio.stdout.read(1024*1024)
        skipcpio.terminate()
        skipcpio.poll()
        return buf

    @staticmethod
    def is_cpio(fn):
        buf = InitrdFile.skipcpio_data(fn)
        if not buf:
            return False

        buftype = typeFile(magic=0x4).getMTypeBuf
        return "ASCII cpio archive" in buftype(buf)

    def get_names(self):
        if not path.exists(self._file):
            # raise IOError
            with open(self._file, 'r'):
                pass
        buftype = typeFile(magic=0x4).getMTypeBuf
        rdtype = buftype(self.skipcpio_data(self._file))
        if "LZ4" in rdtype:
            arch_cmd = '/usr/bin/lz4'
        elif "XZ" in rdtype:
            arch_cmd = '/usr/bin/xz'
        elif "Zstandard" in rdtype:
            arch_cmd = "/usr/bin/zstd"
        else:
            arch_cmd = '/bin/gzip'
        skipcpio_cmd = "/usr/lib/dracut/skipcpio"

        skipcpio = Popen([skipcpio_cmd, self._file], stdout=PIPE, stderr=PIPE,
                   close_fds=True)
        gz = Popen([arch_cmd, "-dc"], stdout=PIPE, stderr=PIPE,
                    stdin=skipcpio.stdout, close_fds=True)
        cpio = Popen(["/bin/cpio", "-tf"], stdout=PIPE, stdin=gz.stdout,
                     stderr=PIPE, close_fds=True)
        try:
            for fn in cpio.stdout.xreadlines():
                yield fn.rstrip()
        finally:
            cpio.terminate()
            gz.terminate()
            skipcpio.terminate()

    def __iter__(self):
        return iter(self.get_names())
