 ############################################################################
 #                                                                          #
 #                              ARCH.PY                                     #
 #                                                                          #
 #           Copyright (C) 2008 - 2010 Ada Core Technologies, Inc.          #
 #                                                                          #
 # This program is free software: you can redistribute it and/or modify     #
 # it under the terms of the GNU General Public License as published by     #
 # the Free Software Foundation, either version 3 of the License, or        #
 # (at your option) any later version.                                      #
 #                                                                          #
 # This program is distributed in the hope that it will be useful,          #
 # but WITHOUT ANY WARRANTY; without even the implied warranty of           #
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            #
 # GNU General Public License for more details.                             #
 #                                                                          #
 # You should have received a copy of the GNU General Public License        #
 # along with this program.  If not, see <http://www.gnu.org/licenses/>     #
 #                                                                          #
 ############################################################################

"""This package contains a single class called Arch that allows the user to
instantiate configuration objects containing information about the system
(native or cross).
"""

import platform
import re
import os.path
from gnatpython import config

UNKNOWN = 'unknown'

# __CPU and __OS are internal classes used only to create namespaces
# and have the possibility to declare attributes such as cpu.name in
# Arch class


class _Arch__CPU:
    """CPU attributes

    ATTRIBUTES
      name: string containing the cpu name
      bits: int representing the number of bits for the cpu or 'unknown'
      endian: 'big', 'little' or 'unknown'
    """

    def __init__(self):
        self.name = UNKNOWN
        self.bits = UNKNOWN
        self.endian = UNKNOWN


class _Arch__OS:
    """OS attributes

    ATTRIBUTES
      name: os name
      version: string containing the os version
      exeext: default executable extension
      dllext: default shared library extension
      is_bareboard: True if the system is bareboard, False otherwise
    """

    def __init__(self):
        self.name = UNKNOWN
        self.version = None
        self.exeext = ''
        self.dllext = ''
        self.is_bareboard = False
        self.kernel_version = None


class Arch:
    """Class that allow user to retrieve os/cpu specific informations

    ATTRIBUTES
      cpu:      CPU information (see _Arch__CPU)
      os:       Operating system information (see _Arch__OS)
      is_hie:   True if the system is a high integrity system
      platform: AdaCore platform product name. Ex: x86-linux
      triplet:  GCC target
      machine:  machine name
      domain:   domain name
      is_host:  True if this is not a cross context
      is_virtual: Set to True if the current system is a virtual one.
                  Currently set only for Solaris containers
    """

    def __init__(self, platform_name=None, version=None, is_host=False,
                 machine=None):
        """Arch constructor

        PARAMETERS
          platform: if None then automatically detect current platform (native)
                    Otherwise should be a valid platform string.
          version:  if None, assume default OS version or find it automatically
                    (native case only).
                    Otherwise should be a valid version string.
          is_host:  if True the system is not a cross one. Default is False
                    except if a platform_name is specified or if the
                    platform_name is equal to the automatically detected one.

        RETURN VALUE
          A Arch instance
        """

        # Create necesarry namespaces using "dummy" classes __CPU and __OS
        self.cpu = __CPU()  # pylint: disable-msg=E0602
        self.os = __OS()   # pylint: disable-msg=E0602

        # Initialize attributes values
        self.platform = platform_name
        self.os.version = version
        self.machine = machine
        self.is_hie = False
        self.is_virtual = False

        if self.platform is None:
            self.is_host = True
        else:
            self.is_host = is_host

        if self.platform is None:
            # In this case we try to guess the host platform
            self.platform = self.__guess_platform()
        else:
            if self.platform == self.__guess_platform():
                # This is a native platform
                self.is_host = True

        if self.is_host:
            # This is host so we can find the machine name using uname fields
            tmp = platform.uname()[1].lower().split('.', 1)
            self.machine = tmp[0]
            if len(tmp) > 1:
                self.domain = tmp[1]
            else:
                self.domain = ""

            # On solaris host detect if we are in a container context or not
            tmp = platform.uname()
            if tmp[0] == 'SunOS' and tmp[3] == 'Generic_Virtual':
                self.is_virtual = True
        else:
            # This is a target name. Sometimes it's suffixed by the host os
            # name. If the name is not a key in config.platform_info try to
            # to find a valid name by suppressing -linux, -solaris or -windows
            if self.platform not in config.platform_info:
                for suffix in ('-linux', '-solaris', '-windows'):
                    if self.platform.endswith(suffix):
                        self.platform = self.platform.replace(suffix, '')
                        break

        # Fill other attributes
        self.__fill_info()

        # Find triplet
        self.triplet = config.build_targets[self.platform]['name'] % \
            self.__get_dict()

    def __get_dict(self):
        """Export os and cpu variables as os_{var} and cpu_{var}

        Returns a dictionary containing os and cpu exported vars
        and self.__dict__ content
        """
        str_dict = self.__dict__.copy()
        for (key, var) in self.os.__dict__.items():
            str_dict["os_" + key] = var
        for (key, var) in self.cpu.__dict__.items():
            str_dict["cpu_" + key] = var
        return str_dict

    def __str__(self):
        """Return a representation string of the object"""
        result = "platform: %(platform)s\n" \
            "machine:  %(machine)s\n" \
            "is_hie:   %(is_hie)s\n" \
            "is_host:  %(is_host)s\n" \
            "triplet:  %(triplet)s\n" \
            "OS\n" \
            "   name:          %(os_name)s\n" \
            "   version:       %(os_version)s\n" \
            "   exeext:        %(os_exeext)s\n" \
            "   dllext:        %(os_dllext)s\n" \
            "   is_bareboard:  %(os_is_bareboard)s\n" \
            "CPU\n" \
            "   name:   %(cpu_name)s\n" \
            "   bits:   %(cpu_bits)s\n" \
            "   endian: %(cpu_endian)s" % self.__get_dict()
        return result

    def __fill_info(self):
        """Internal function that fill info related to the cpu, os, ...

        PARAMETERS
          None

        RETURN VALUE
          None

        REMARKS
          None
        """
        self.os.name = config.platform_info[self.platform]['os']
        self.cpu.name = config.platform_info[self.platform]['cpu']
        self.is_hie = config.platform_info[self.platform]['is_hie']

        self.cpu.bits = config.cpu_info[self.cpu.name]['bits']
        self.cpu.endian = config.cpu_info[self.cpu.name]['endian']

        self.os.is_bareboard = config.os_info[self.os.name]['is_bareboard']
        self.os.exeext = config.os_info[self.os.name]['exeext']
        self.os.dllext = config.os_info[self.os.name]['dllext']

        # If version is not given by the user guess it or set it to the
        # default (cross case)
        if self.is_host and self.os.version is None:
            self.__guess_os_version()
        if self.os.version is None:
            self.os.version = config.os_info[self.os.name]['version']

    def __guess_platform(self):
        """
        Internal function that guess base on uname system call the
        current platform

        PARAMETERS
          None

        RETURN VALUE
          return a string object containing the platform name

        REMARKS
          None
        """

        def re_contains(left, right):
            """Returns right in left (regexp aware)"""
            if re.match(left + '$', right) or \
                    re.match('^' + left, right):
                return True
            else:
                return False

        def re_endswith(left, right):
            """Returns right.endswith(left) (regexp aware)"""
            return re.match(left + '$', right)

        def guess(os_name, p_uname):
            """Guess based on os_name"""
            for p_name in config.host_guess:
                p_config = config.host_guess[p_name]
                if p_config['os'] is not None:
                    if re_contains(p_config['os'], os_name):
                        if p_config['cpu'] is None or \
                                re_endswith(p_config['cpu'], p_uname[4]) or \
                                re_endswith(p_config['cpu'], p_uname[5]):
                            # The p_name config matched

                            if p_name in config.host_aliases:
                                return config.host_aliases[p_name]
                            else:
                                return p_name
            # wrong guess
            return None

        # First look for matching machine name
        for p_name in config.host_guess:
            if config.host_guess[p_name]['machine'] is not None:
                if re_endswith(config.host_guess[p_name]['machine'] + '$',
                               self.machine):
                    return p_name

        # Else we need to guess
        uname = platform.uname()

        p_name = guess(uname[0], uname)
        if p_name is not None:
            return p_name

        p_name = guess(uname[2], uname)
        if p_name is not None:
            return p_name

        # Not found !
        return UNKNOWN

    def __guess_os_version(self):
        """Internal function used to guess the host OS version/dist

        PARAMETERS
          None

        RETURN VALUE
          None

        REMARKS
          Set the self.os.version attribute and on some platform the
          self.os.kernel_version
        """
        if self.os.name in ('freebsd', 'tru64'):
            # Do not compute OS version but read config.os_info table
            return

        uname = platform.uname()
        if self.os.name == 'darwin':
            self.os.version = uname[2]
        elif self.os.name == 'linux':
            self.os.kernel_version = uname[2]
            if os.path.isfile('/etc/redhat-release'):
                # RedHat distributions
                with open('/etc/redhat-release') as rel_f:
                    content = rel_f.read().strip()
                    for sub in (('\(.*', ''),
                                (' ', ''),
                                ('Linux', ''),
                                ('release', ''),
                                ('Enterprise', ''),
                                ('AdvancedServer', 'AS'),
                                ('Server', 'ES'),
                                ('RedHat', 'rh'),
                                ('5\.[0-9]', '5')):
                        content = re.sub(sub[0], sub[1], content)
                    self.os.version = content
            elif os.path.isfile('/etc/SuSE-release'):
                # Suse distributions
                release = open('/etc/SuSE-release', 'r')
                for line in release:
                    version = re.search('VERSION = ([0-9\.]+)', line)
                    if version is not None:
                        release.close()
                        self.os.version = 'suse' + version.group(1)
                        break
                release.close()
                if self.os.version is None:
                    self.os.version = 'suse'
            elif os.path.isfile('/etc/lsb-release'):
                # /etc/lsb-release is present on the previous distrib
                # but is not useful. On ubuntu it contains the
                # distrib number
                release = open('/etc/lsb-release', 'r')
                distrib_name = ''
                distrib_version = ''
                for line in release:
                    distrib_id = re.search('DISTRIB_ID=(.+)', line.rstrip())
                    if distrib_id is not None:
                        distrib_name = distrib_id.group(1).lower()
                    else:
                        distrib_release = re.search('DISTRIB_RELEASE=(.*)',
                                                    line.rstrip())
                        if distrib_release is not None:
                            distrib_version = distrib_release.group(1)

                release.close()
                if distrib_name:
                    self.os.version = distrib_name + distrib_version
        elif self.os.name == 'aix':
            self.os.version = uname[3] + '.' + uname[2]
        elif self.os.name == 'hp-ux':
            version = uname[2]
            if version[0:2] == 'B.':
                version = version[2:]
            self.os.version = version
        elif self.os.name == 'irix':
            self.os.version = uname[2]
        elif self.os.name == 'lynxos':
            self.os.version = ''
        elif self.os.name == 'solaris':
            self.os.version = '2' + uname[2][1:]
        elif self.os.name == 'windows':
            self.os.version = uname[2].replace('Server', '')
            self.os.kernel_version = uname[3]
        return

if __name__ == "__main__":
    print Arch()
