// Copyright 2021 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.

package testcases

import (
	"time"

	"github.com/pingcap/test-infra/caselib/pkg/model/workload"
	"github.com/pingcap/test-infra/caselib/pkg/spec"
	"github.com/pingcap/test-infra/caselib/pkg/steps"
	"github.com/pingcap/test-infra/caselib/pkg/utils"
	_ "github.com/pingcap/test-infra/sdk/resource/impl/k8s"
)

func init() {
	var (
		name                 = "dm_tiup_scale_in"
		env                  = newCommonEnvWithTiup()
		dmVersion            string
		workloadTiupDmOption = workload.TiupDmOption{DmName: "testdm", ControlNode: "tiup-peer", Version: &dmVersion, TopoFile: "global:\n  user: \"tidb\"\n  ssh_port: 22\n  deploy_dir: \"/dm-deploy\"\n  data_dir: \"/dm_data\"\nmaster_servers:\n  - host: tiup-peer\n    port: 8261\n    peer_port: 8291\nworker_servers:\n  - host: tiup-peer\n    port: 8262\n  - host: tiup-peer\n    port: 8263\n\nmonitoring_servers:\n  - host: tiup-peer\ngrafana_servers:\n  - host: tiup-peer\n"}
		mirrorAdress         = "http://staging.tiup-server.pingcap.net"
		// workloadTiupDmScaleOutOption = workload.TiupDmOption{DmName: "testdm", ControlNode: "tiup-peer", TopoFile: "worker_servers:\n  - host: tiup-peer\n    port: 8263\n"}
		workloadTiupDmScaleInOption = workload.TiupDmOption{DmName: "testdm", ControlNode: "tiup-peer", TopoFile: "tiup-peer:8263"}
	)

	var _ = AddTestCase(spec.CaseName(name), func() steps.Step {
		env.init().b.
			LoadParamFromEnv(utils.ParamPrefix+"dmVersion", &dmVersion).
			CreateDatabase(env.UpStreams[0], name).
			DmRunWorkload(env.UpStreams[0], env.Dm, env.Workload, Spec.GetWorkloadOption(workload.CommandTypePrepare)).
			RunTiupDmMirrorSet(workload.TiupDmMirrorOption{MirrorAdress: &mirrorAdress}, env.Tiup).
			DeployTiupDmCluster(workloadTiupDmOption, env.Tiup).
			ScaleInTiupDmCluster(workloadTiupDmScaleInOption, env.Tiup).
			TiupDmCreateSources(env.Dm, env.DmHost, Path.SourcePaths).
			TiupDmStartTasks(env.Dm, env.DmHost, Path.TaskPaths).
			Sleep(5*time.Minute).
			DmCheckSyncDiff(env.Dm, env.SyncDiff, env.DmHost, Path.DiffPaths[0])
		return env.toBuilder().Build()
	},
	)
}
