package tidbcluster

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"github.com/pingcap/test-infra/sdk/resource"

	"github.com/pingcap/test-infra/sdk/e2etest/framework"
)

var _ = Describe("BR Test", func() {
	Context("BR.Create", func() {
		f := framework.NewDefaultFramework("testbed-br-create")

		It("BR's testbed should equal to testbed's name", func() {
			br := f.CreateBR(f.CreateTestbed())
			Expect(br.Testbed).Should(Equal(f.Testbed()))
		})

		It("BR should be ready after a while", func() {
			br := f.CreateBR(f.CreateTestbed())
			err := f.WaitForBRReady(br, framework.TestContext.ResourceWaitReadyTimeout)
			framework.ExpectNoError(err)
		})
	})

	Context("BR.Get", func() {
		f := framework.NewDefaultFramework("testbed-br-get")

		It("BR's testbed should equal to testbed's name", func() {
			br := f.CreateBR(f.CreateTestbed())
			br = f.GetBR(br.Handle())

			Expect(br.Testbed).Should(Equal(f.Testbed()))
		})

		It("BR should be ready after a while", func() {
			br := f.CreateBR(f.CreateTestbed())
			br = f.GetBR(br.Handle())

			err := f.WaitForBRReady(br, framework.TestContext.ResourceWaitReadyTimeout)
			framework.ExpectNoError(err)
		})
	})

	Context("BR.Archive", func() {
		f := framework.NewDefaultFramework("testbed-br-archive")

		It("BR.Archive should work well", func() {
			br := f.CreateBR(f.CreateTestbed())
			br = f.GetBR(br.Handle())

			err := f.WaitForBRReady(br, framework.TestContext.ResourceWaitReadyTimeout)
			framework.ExpectNoError(err)

			_, _, _, err = br.Exec(resource.WorkloadNodeExecOptions{Command: "echo test-infra > /tmp/br.log.1"})
			framework.ExpectNoError(err)
			var data []string

			f.ArchiveBR(br.Handle(), f.Archiver(&data))
			Expect(len(data)).Should(Equal(1))
			Expect(data[0]).Should(ContainSubstring("test-infra"))
		})
	})

	Context("BR.Delete", func() {
		f := framework.NewDefaultFramework("testbed-br-delete")

		It("BR's delete should clean all resources", func() {
			br := f.CreateBR(f.CreateTestbed())

			f.DeleteBRWaited(br)

			pods := f.AllPods()
			Expect(len(pods.Items)).Should(Equal(0))
			Expect(len(f.AllPVCs().Items)).Should(Equal(0))
			Expect(len(f.AllServices().Items)).Should(Equal(0))
			Expect(len(f.AllConfigmaps().Items)).Should(Equal(1))
		})
	})

	Context("BR.Exec", func() {
		f := framework.NewDefaultFramework("testbed-br-exec")

		It("BR's /br --version", func() {
			br := f.CreateBR(f.CreateTestbed())
			f.WaitForBRReady(br, framework.TestContext.ResourceWaitReadyTimeout)

			stdout, _, _, _ := br.Exec(resource.WorkloadNodeExecOptions{Command: "/br --version"})
			Expect(stdout).Should(Equal(`Release Version: v5.0.1
Git Commit Hash: b3bd5495369244cfb1d3f2c49763a7fdb55d4ecd
Git Branch: heads/refs/tags/v5.0.1
Go Version: go1.13
UTC Build Time: 2021-04-23 06:02:57
Race Enabled: false`))
		})
	})
})
