package core

import (
	"context"
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
	"testing"

	"github.com/pingcap/schrodinger/buildbot/config"
	"github.com/pingcap/schrodinger/util"
	"github.com/stretchr/testify/assert"
)

func TestAgentHandler(t *testing.T) {
	name := "pd"
	binaryName := "pd-server"
	latestGitHash, err := util.GetHashByBranchAndTag("master", "", "pd",
		config.GetBuildConfig().BaseConfig.DownloadAddr)
	if err != nil {
		assert.NoError(t, err)
	}
	binaryAddr := fmt.Sprintf("%s/download/builds/pingcap/pd/%s/centos7/pd-server.tar.gz",
		config.GetBuildConfig().BaseConfig.DownloadAddr, latestGitHash)
	presetDaemonDir := "preset_daemon"
	info := &DaemonInfo{
		Name:       name,
		BinaryName: binaryName,
	}

	defer func() {
		os.RemoveAll(name)
		os.RemoveAll("preset_daemon")
	}()

	// test dummy addr case
	os.RemoveAll(name)
	info.BinaryAddr = "dummy_addr"
	_, err = jail(context.Background(), info)
	assert.Error(t, err)

	// test normal case
	info.BinaryAddr = binaryAddr
	_, err = jail(context.Background(), info)
	assert.NoError(t, err)

	// test preset daemon case
	info.BinaryAddr = "dummy_addr"
	os.RemoveAll(presetDaemonDir)
	presetDaemonDir, err = filepath.Abs(presetDaemonDir)
	assert.NoError(t, err)
	os.MkdirAll(presetDaemonDir, 0755)
	pdDaemonDir := path.Join(presetDaemonDir, name)
	err = os.Rename(name, pdDaemonDir)
	assert.NoError(t, err)
	_, err = jail(context.Background(), info)
	assert.NoError(t, err)

	dirs, err := ioutil.ReadDir(pdDaemonDir)
	assert.NoError(t, err)
	for _, dir := range dirs {
		if dir.IsDir() && dir.Name() == "bin" {
			binaries, err := ioutil.ReadDir(path.Join(pdDaemonDir, "bin"))
			assert.NoError(t, err)
			for _, binary := range binaries {
				if !binary.IsDir() && binary.Name() == binaryName {
					return
				}
			}
		}
	}

	t.FailNow()
}
