#!/usr/bin/env python3
# -*- coding:utf-8 -*-
try:
    import os
    import sys
    import re
    sys.path.append(sys.path[0] + "/../../../")
    from gspylib.os.platform import support_platform
except Exception as ie:
    sys.exit("[GAUSS-52200] : Unable to import module: %s." % str(ie))


class GetPlatform():
    """
    get os distname, version, currentid
    """

    def __init__(self):
        pass

    def __read_os_release(self, distname, version, id):
        '''
        function: Some operating systems do not have the xx-release file.
                  Therefore, you can use the os-release file to obtain operating system information.
                  For example, SUSE 15 does not have a /etc/SuSE-release file.
        '''
        distname_regex = re.compile(r'ID="([^"]*)"')
        version_regex = re.compile(r'VERSION_ID="([^"]*)"')

        with open('/etc/os-release') as fp:
            info = fp.readlines()

        for line in info:
            m = distname_regex.match(line.replace('\n', ''))
            if m is not None:
                distname = m.groups()[0]

            m = version_regex.match(line.replace('\n', ''))
            if m is not None:
                version = m.groups()[0]

        if distname == 'sles':
            distname = 'SuSE'
            version = version.split('.')[0]
            id = 'x86_64'

        return distname, version, id

    def dist_try_harder(self, distname, version, id):

        if os.path.exists('/var/adm/inst-log/info'):
            # SuSE Linux stores distribution information in that file
            info = open('/var/adm/inst-log/info').readlines()
            distname = 'SuSE'
            for line in info:
                tv = str.split(line)
                if len(tv) == 2:
                    tag, value = tv
                else:
                    continue
                if tag == 'MIN_DIST_VERSION':
                    version = str.strip(value)
                elif tag == 'DIST_IDENT':
                    values = str.split(value, '-')
                    id = values[2]
            return distname, version, id

        if os.path.exists('/etc/.installed'):
            # Caldera OpenLinux has some infos in that file (thanks to Colin Kong)
            info = open('/etc/.installed').readlines()
            for line in info:
                pkg = str.split(line, '-')
                if len(pkg) >= 2 and pkg[0] == 'OpenLinux':
                    # XXX does Caldera support non Intel platforms ? If yes,
                    #     where can we find the needed id ?
                    return 'OpenLinux', pkg[1], id

        if os.path.isdir('/usr/lib/setup'):
            # Check for slackware verson tag file (thanks to Greg Andruk)
            verfiles = os.listdir('/usr/lib/setup')
            for n in range(len(verfiles) - 1, -1, -1):
                if verfiles[n][:14] != 'slack-version-':
                    del verfiles[n]
            if verfiles:
                verfiles.sort()
                distname = 'slackware'
                version = verfiles[-1][14:]
                return distname, version, id

        if os.path.exists('/etc/os-release'):
            distname, version, id = self.__read_os_release('', '', '')
            if distname != '' and version != '':
                return distname, version, id

        return distname, version, id

    release_filename = re.compile(r'(\w+)[-_](release|version)')
    lsb_release_version = re.compile(r'(.+)'
                                     ' release '
                                     '([\d.]+)'
                                     '[^(]*(?:\((.+)\))?')
    release_version = re.compile(r'([^0-9]+)'
                                 '(?: release )?'
                                 '([\d.]+)'
                                 '[^(]*(?:\((.+)\))?')

    def parse_release_file(self, firstline):

        version = ''
        id = ''

        # Parse the first line
        m = self.lsb_release_version.match(firstline)
        if m is not None:
            # LSB format: "distro release x.x (codename)"
            return tuple(m.groups())

        # Pre-LSB format: "distro x.x (codename)"
        m = self.release_version.match(firstline)
        if m is not None:
            return tuple(m.groups())

        # Unkown format... take the first two words
        left_str = str.split(str.strip(firstline))
        if left_str:
            version = left_str[0]
            if len(left_str) > 1:
                id = left_str[1]
        return '', version, id

    def linux_distribution(self, distname='', version='', id='',
                           supported_dists=support_platform.SUPPORTED_DISTS,
                           full_distribution_name=1):
        try:
            etc = os.listdir('/etc')
        except os.error:
            # Probably not a Unix system
            return distname, version, id
        etc.sort()
        for file in etc:
            if os.path.islink('/etc/' + file):
                continue
            m = self.release_filename.match(file)
            if m is not None:
                _distname, dummy = m.groups()
                if _distname == "asianux":
                    distname = "centos"
                    break
                if _distname in supported_dists:
                    distname = _distname
                    break
        else:
            return self.dist_try_harder(distname, version, id)

        # Read the first line
        f = open('/etc/' + file, 'r')
        firstline = f.readline()
        f.close()
        _distname, _version, _id = self.parse_release_file(firstline)

        if _distname and full_distribution_name:
            distname = _distname
        if _version:
            version = _version
        if _id:
            id = _id
        return distname, version, id

    def dist(self, distname='', version='', id='',
             supported_dists=support_platform.SUPPORTED_DISTS):
        return self.linux_distribution(distname, version, id,
                                       supported_dists,
                                       full_distribution_name=0)
