# -*- 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
from subprocess import Popen, PIPE
from calculate.lib.cl_lang import setLocalTranslate

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


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

    def __init__(self, _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 ""

    def get_names(self):
        if not path.exists(self._file):
            # raise IOError
            open(self._file)
        ftype = typeFile(magic=0x4).getMType
        rdtype = ftype(self._file)
        if "LZ4" in rdtype:
            arch_cmd = '/usr/bin/lz4'
        elif "XZ" in rdtype:
            arch_cmd = '/usr/bin/xz'
        else:
            arch_cmd = '/bin/gzip'
        gz = Popen([arch_cmd, "-dc", self._file], stdout=PIPE, stderr=PIPE,
                   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()

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