#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import subprocess

# Translations

MSG_HOSTNAME = {
    "en": "Hostname contains invalid characters: '%s'",
    "tr": "Makine ismi geçersiz karakterler içeriyor: '%s'",
    "fr": "Le nom d'hôte contient des caractères invalides: '%s'",
    "nl": "Hostnaam bevat ongeldige lettertekens: '%s'",
}

# Translations End

HEADER_DEFAULT = """# Default DNS settings
#
"""

HEADER_DYNAMIC = """# This file is automatically generated by SCOM
# Use network-manager to set default DNS settings or edit "resolv.default.conf"
#
# Bu dosya SCOM tarafından otomatik olarak üretilir.
# Öntanımlı DNS ayalarını değiştirmek için network-manager uygulamasını kullanın
# veya "resolv.default.conf" dosyasını düzenleyin.
#
"""
ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ascii_letters = ascii_lowercase + ascii_uppercase
digits = '0123456789'

MAX_SERVERS = 3

HOST_CHARS = ascii_letters + digits + '.' + '_' + '-'

NAME_PATH = "/etc/env.d/01hostname"
CMD_ENV = "/sbin/update-environment"
HOSTS_PATH = "/etc/hosts"

RESOLV_USER = "/etc/resolv.default.conf"
RESOLV_INARYLINUX = "/usr/share/baselayout/resolv.conf"

def getSearchDomain():
    if not os.access(RESOLV_USER, os.R_OK):
        return None
    for line in file(RESOLV_USER):
        line = line.strip()
        if line.startswith("search"):
            return line.split()[1]
    return None

def getSulinNameServers():
    servers = []
    if not os.access(RESOLV_INARYLINUX, os.R_OK):
        return servers
    for line in file(RESOLV_INARYLINUX):
        line = line.strip()
        if line.startswith("nameserver"):
            ip = line.split()[1]
            if ip not in servers:
                servers.append(ip)
    return servers

# Network.Stack methods

def getNameServers():
    servers = []
    if not os.access(RESOLV_USER, os.R_OK):
        return servers
    for line in file(RESOLV_USER):
        line = line.strip()
        if line.startswith("nameserver"):
            ip = line.split()[1]
            if ip not in servers:
                servers.append(ip)
    return servers

def setNameServers(nameservers, searchdomain):
    f = open("/etc/resolv.default.conf", "w")
    f.write(HEADER_DEFAULT)

    for server in nameservers:
        f.write("nameserver %s\n" % server)

    if searchdomain:
        f.write("searchdomain %s\n" % searchdomain)

    f.close()

def useNameServers(nameservers, searchdomain):
    # Append default name servers
    nameservers.extend(getNameServers())
    nameservers.extend(getSulinNameServers())

    servers = []
    for server in nameservers:
        if server not in servers:
            servers.append(server)

    f = open("/etc/resolv.conf", "w")
    f.write(HEADER_DYNAMIC)

    for server in servers[:MAX_SERVERS]:
        f.write("nameserver %s\n" % server)

    if searchdomain:
        f.write("search %s\n" % searchdomain)
    elif getSearchDomain():
        f.write("search %s\n" % getSearchDomain())

    f.close()

def registerNameServers(iface, nameservers, searchdomain):
    useNameServers(nameservers, searchdomain)

def unregisterNameServers(iface, nameservers, searchdomain):
    # Remove nameservers from list
    nameservers = getNameServers()
    for server in nameservers:
        try:
            nameservers.remove(server)
        except ValueError:
            pass
    # Set search domain to "" if it's active one
    if searchdomain == getSearchDomain():
        searchdomain = ""
    useNameServers(nameservers, searchdomain)

def flushNameCache():
    pass

def getHostName():
    cmd = subprocess.Popen(["/usr/bin/hostname"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    a = cmd.communicate()
    if a[1] == "":
        return a[0].rstrip("\n")
    return ""

def setHostName(hostname):
    if not hostname:
        return
    invalid = filter(lambda x: not x in HOST_CHARS, hostname)
    if len(invalid) > 0:
        fail(_(MSG_HOSTNAME) % ("".join(invalid)))

    # hostname
    if os.path.exists(NAME_PATH):
        import re
        f = open(NAME_PATH)
        data = f.read()
        f.close()
        data = re.sub('HOSTNAME="(.*)"', 'HOSTNAME="%s"' % hostname, data)
    else:
        data = 'HOSTNAME="%s"\n' % hostname
    f = open(NAME_PATH, "w")
    f.write(data)
    f.close()

    # hosts
    f = open(HOSTS_PATH)
    data = f.readlines()
    f.close()
    f = file(HOSTS_PATH, "w")
    flag = 1
    for line in data:
        if line.startswith("127.0.0.1"):
            line = "127.0.0.1 localhost %s\n" % hostname
            flag = 0
        f.write(line)
    if flag:
        f.write("127.0.0.1 localhost %s\n" % hostname)
    f.close()

    # update environment
    os.system(CMD_ENV)
