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

#Copyright 2008 Calculate Pack, http://www.calculate-linux.ru
#
#  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 re
import os
import types
import cl_utils
import cl_base

class fillVars(object, cl_base.glob_attr):

    def get_os_net_domain(self):
        ''' Определим домен'''
        domain=self._runos("%s hostname -d 2>&1"%self.path_env)
        if not domain:
            print _("Error:") + " " +_("Not found domain name")
            print _("Command 'hostname -d' returns an empty value")
            cl_base.exit(1)
        elif re.search("^hostname: ",domain):
            return "local"
        else:
            return domain

    def get_os_linux_shortname(self):
        '''Получить переменную короткого названия системы'''
        path = '/etc/issue'
        sp="""Welcome to \\\\n.\\\\O \(([a-zA-Z ]+) ([^\s\)]+)"""
        res=self._runos('%scat %s | grep "Welcome to "'%\
                (self.path_env, path))
        dist_ver = {'CLD':"Calculate Linux Desktop",
                    'CDS':"Calculate Directory Server",
                    'AcoolA':"Calculate Web Server"}
        if res:
            if re.search(sp,res):
                vals=re.search(sp,res).groups()
                issuename=vals[0]
                for i in dist_ver.keys():
                    if dist_ver[i]==issuename:
                        return i
                spl=issuename.split(" ")
                nname=""
                if len(spl)>1:
                    for i in spl:
                        nname+=i[1]
                    return nname
                else:
                    return issuename
        return "CLD"


    def get_os_net_hostname(self):
        '''Считать имя компьютера net_host'''
        hostname=self._runos("""%s hostname -s 2>&1"""%self.path_env)
        #Set('net_host',hostname, True)
        #упрощенный вариант, следует выполнять только если не указан домен
        #в системе
        if re.search("^hostname: ",hostname):
            hostname=self._runos("""%s hostname 2>&1"""%self.path_env)
        if re.search("^hostname: ",hostname):
            return self.Get('os_linux_shortname')
        else:
            if hostname=='livecd':
                return self.Get('os_linux_shortname')
        return hostname

    # Разрешенные сети (в данном случае все сети)
    def get_os_net_allow(self):
        """Разрешенные сети разделитель запятая"""
        net={'255.255.0.0':'/16',
            '255.255.255.0':'/24',
            '255.255.255.128':'/25',
            '255.255.255.252':'/30',
            '255.255.255.255':''}
        networks=[]
        netInterfaces=cl_utils.getdirlist("/sys/class/net/")
        for i in netInterfaces:
            res=self._runos("/sbin/ifconfig %s"%i)
            for j in res:
                s_ip=re.search('addr:([0-9\.]+).+Bcast:.+Mask:([0-9\.]+)' ,j)
                if s_ip:
                    ip, netmask=s_ip.groups()
                    ip=ip.split('.')
                    if ip[0]=='10' or\
                        (ip[0]=='172' and int(ip[1])>=16 and int(ip[1])<=31)or\
                        (ip[0]=='192' and ip[1]=='168'):
                        if netmask=='255.255.255.255':
                            networks.append(ip)
                        elif netmask=='255.255.255.252':
                            networks.append(ip[0]+"."+ip[1]+"."+ip[2]+"."+\
                                            "252"+net[netmask])
                        elif netmask=='255.255.255.128':
                            networks.append(ip[0]+"."+ip[1]+"."+ip[2]+"."+\
                                            "128"+net[netmask])
                        elif netmask=='255.255.255.0':
                            networks.append(ip[0]+"."+ip[1]+"."+ip[2]+"."+"0"+\
                                            net[netmask])
                        elif netmask=='255.255.0.0':
                            networks.append(ip[0]+"."+ip[1]+".0.0"+net[netmask])
        return ",".join(networks)

    def get_os_locale_locale(self):
        """локаль (прим: ru_RU.UTF-8)"""
        if os.environ.has_key("LANG"):
            return os.environ["LANG"]
        else:
            return "en_US.UTF-8"

    def get_os_locale_lang(self):
        """язык (прим: ru_RU)"""
        locale = self.Get("os_locale_locale")
        if locale:
            return locale.split(".")[0]
        return ""

    def get_os_locale_language(self):
        """язык (прим: ru)"""
        lang = self.Get("os_locale_lang")
        if lang:
            return lang.split("_")[0]
        return ""

    def get_os_arch_machine(self):
        """архитектура процессора"""
        march = self._runos("""%s uname -m"""%self.path_env)
        return march

    def get_os_root_dev(self):
        """корневой раздел файловой системы"""
        for record in open('/proc/cmdline','rb').readlines():
            re_res=re.search('^root=(\/dev\/[a-z]+[0-9]).*',record.strip())
            if re_res:
                return re_res.group(1)
            else:
                mountLunes = self._runos("""%s mount"""%self.path_env)
                if type(mountLunes) == types.ListType:
                    root_dev = mountLunes[0].split("on / type")[0].strip()
                    if root_dev:
                        return root_dev
                return ""

    def get_os_root_type(self):
        """тип носителя (ram, hdd, livecd)"""
        mountLunes = self._runos("""%s mount"""%self.path_env)
        rootType = "hdd"
        if type(mountLunes) == types.ListType:
            for line in mountLunes:
                if "/dev/loop0 on / type" in line:
                    rootType = "ram"
                    break
            if rootType == "ram" and os.path.exists("/mnt/livecd"):
                rootType = "livecd"
                return rootType
            rootDev = self.Get("os_root_dev")
            if rootType != "ram" and rootDev:
                slpRootDev = rootDev.split("/dev/")
                if len(slpRootDev) == 2:
                    rDev = slpRootDev[1]
                    devLines = self._runos("%s LANG=C ls -la /dev/disk/by-id/"\
                                           %self.path_env)
                    if type(devLines) == types.ListType:
                        for line in devLines:
                            if rDev in line and "usb-" in line:
                                rootType = "usb-hdd"
                                break
            if rootType == "ram":
                rootType = "hdd"
            return rootType
        else:
            return ""