# This file is part of cloud-init. See LICENSE file for license information.

import re

import pytest

from cloudinit.distros.parsers import resolv_conf

BASE_RESOLVE = """
; generated by /sbin/dhclient-script
search blah.yahoo.com yahoo.com
nameserver 10.15.44.14
nameserver 10.15.30.92
"""
BASE_RESOLVE = BASE_RESOLVE.strip()


class TestResolvHelper:
    def test_parse_same(self):
        rp = resolv_conf.ResolvConf(BASE_RESOLVE)
        rp_r = str(rp).strip()
        assert BASE_RESOLVE == rp_r

    def test_local_domain(self):
        rp = resolv_conf.ResolvConf(BASE_RESOLVE)
        assert rp.local_domain is None

        rp.local_domain = "bob"
        assert "bob" == rp.local_domain
        assert "domain bob" in str(rp)

    def test_nameservers(self):
        rp = resolv_conf.ResolvConf(BASE_RESOLVE)

        # Start with two nameservers that already appear in the configuration.
        assert "10.15.44.14" in rp.nameservers
        assert "10.15.30.92" in rp.nameservers

        # Add a third nameserver and verify it appears in the resolv.conf.
        rp.add_nameserver("10.2")
        assert "10.2" in rp.nameservers
        assert "nameserver 10.2" in str(rp)
        assert len(rp.nameservers) == 3

        # Add a fourth nameserver and verify it appears in the resolv.conf.
        rp.add_nameserver("10.3")
        assert "10.3" in rp.nameservers
        assert "nameserver 10.3" in str(rp)
        assert len(rp.nameservers) == 4

    def test_search_domains(self):
        rp = resolv_conf.ResolvConf(BASE_RESOLVE)
        assert "yahoo.com" in rp.search_domains
        assert "blah.yahoo.com" in rp.search_domains
        rp.add_search_domain("bbb.y.com")
        assert "bbb.y.com" in rp.search_domains
        assert re.search(r"search(.*)bbb.y.com(.*)", str(rp))
        assert "bbb.y.com" in rp.search_domains
        rp.add_search_domain("bbb.y.com")
        assert len(rp.search_domains) == 3
        rp.add_search_domain("bbb2.y.com")
        assert len(rp.search_domains) == 4
        rp.add_search_domain("bbb3.y.com")
        assert len(rp.search_domains) == 5
        rp.add_search_domain("bbb4.y.com")
        assert len(rp.search_domains) == 6
        with pytest.raises(ValueError):
            rp.add_search_domain("bbb5.y.com")
        assert len(rp.search_domains) == 6
