package dnsresolver_test

import (
	fakesys "github.com/cloudfoundry/bosh-utils/system/fakes"
	. "github.com/onsi/ginkgo/v2"
	. "github.com/onsi/gomega"

	. "github.com/cloudfoundry/bosh-agent/v2/platform/net/dnsresolver"
)

var _ = Describe("systemdConfResolver", func() {
	var (
		fs              *fakesys.FakeFileSystem
		cmdRunner       *fakesys.FakeCmdRunner
		systemdResolver DNSResolver
	)

	BeforeEach(func() {
		fs = fakesys.NewFakeFileSystem()
		cmdRunner = fakesys.NewFakeCmdRunner()
		systemdResolver = NewSystemdResolver(fs, cmdRunner)
	})

	Context("when /etc/systemd/resolved.conf.d/10-bosh.conf contains at least one dns server", func() {
		BeforeEach(func() {
			err := fs.WriteFileString("/etc/systemd/resolved.conf.d/10-bosh.conf", `
				[Resolve]
				DNS=8.8.8.8 9.9.9.9`)
			Expect(err).NotTo(HaveOccurred())
		})

		It("returns nil", func() {
			err := systemdResolver.Validate([]string{"8.8.8.8", "10.10.10.10"})
			Expect(err).ToNot(HaveOccurred())
		})
	})

	Context("when reading /etc/systemd/resolved.conf.d/10-bosh.conf failed", func() {
		It("returns error", func() {
			err := systemdResolver.Validate([]string{"8.8.8.8", "9.9.9.9"})
			Expect(err).To(HaveOccurred())
			Expect(err.Error()).To(ContainSubstring("Reading /etc/systemd/resolved.conf.d/10-bosh.conf"))
		})
	})

	Context("when /etc/systemd/resolved.conf.d/10-bosh.conf does not contain any of the dns servers specified in the manifest", func() {
		BeforeEach(func() {
			err := fs.WriteFileString("/etc/systemd/resolved.conf.d/10-bosh.conf", `DNS=6.6.6.6`)
			Expect(err).NotTo(HaveOccurred())
		})

		It("returns error", func() {
			err := systemdResolver.Validate([]string{"8.8.8.8", "9.9.9.9"})
			Expect(err).To(HaveOccurred())
			Expect(err.Error()).To(ContainSubstring("None of the DNS servers that were specified in the manifest were found in /etc/systemd/resolved.conf.d/10-bosh.conf."))
		})
	})

	Context("when there are configured DNS servers", func() {
		It("writes DNS to /etc/systemd/resolved.conf.d/10-bosh.conf", func() {
			err := systemdResolver.SetupDNS([]string{"8.8.8.8", "9.9.9.9"})
			Expect(err).ToNot(HaveOccurred())

			resolvConfBase := fs.GetFileTestStat("/etc/systemd/resolved.conf.d/10-bosh.conf")
			Expect(resolvConfBase).ToNot(BeNil())

			expectedResolvConfBase := `# Generated by bosh-agent
[Resolve]
DNS=8.8.8.8 9.9.9.9`
			Expect(resolvConfBase.StringContents()).To(ContainSubstring(expectedResolvConfBase))
			Expect(cmdRunner.RunCommands[0]).To(Equal([]string{"systemctl", "restart", "systemd-resolved"}))
		})
	})

	Context("when no DNS servers are configured", func() {
		It("return nil", func() {
			err := systemdResolver.SetupDNS([]string{})
			Expect(err).NotTo(HaveOccurred())
		})
	})

})
