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

# Copyright 2008-2012 Calculate Ltd. 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 socket
from calculate.lib.datavars import Variable,VariableError,ReadonlyVariable
from calculate.lib.utils import ip
from calculate.lib.utils.files import listDirectory

class VariableOsNetHostname(ReadonlyVariable):
    """
    Hostname
    """
    def get(self):
        return self.Get('os_net_fqdn').partition('.')[0]

class VariableOsNetDomain(ReadonlyVariable):
    """
    Domain name
    """
    def get(self):
        return self.Get('os_net_fqdn').partition('.')[2]

class VariableOsNetFqdn(ReadonlyVariable):
    """
    Full qualited domain name
    """
    def get(self):
        fqdn = socket.getfqdn()
        if not fqdn:
            fqdn = "calculate"
        if not "." in fqdn:
            return "%s.local"%fqdn
        else:
            return fqdn

class VariableOsNetAllow(ReadonlyVariable):
    """
    Allowed networks (comma delimeter)
    """

    def get(self):
        """Allowed networks"""
        networks=[]
        netInterfaces=self.Get("os_net_interfaces")
        for i in netInterfaces:
            ipaddr, mask = ip.getIp(i),ip.cidrToMask(ip.getMask(i))
            if ipaddr and mask:
                networks.append(ip.getIpNet(ipaddr, mask))
            else:
                networks.append("")
        return ",".join(filter(lambda x:x,networks))

class VariableOsNetIp(ReadonlyVariable):
    """
    IP for all network interfaces (comma delimeter)
    """
    def get(self):
        """All computer ip addresses, comma delimeter"""
        IPs = []
        netInterfaces=self.Get("os_net_interfaces")
        for i in netInterfaces:
            ipaddr = ip.getIp(i)
            if ipaddr:
                IPs.append(ipaddr)
        return ",".join(IPs)

class VariableOsNetInterfaces(ReadonlyVariable):
    """
    Network interfaces
    """
    type = "list"

    def get(self):
        """All net interfaces"""
        return ip.getInterfaces()
