package main

import (
	"flag"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/pingcap/schrodinger-test/nemesis/arsenal"
	"github.com/pingcap/schrodinger-test/util"
	client "github.com/pingcap/schrodinger/pkg/test_client"
	"golang.org/x/net/context"
)

var (
	defaultPushMetricsInterval   = 15 * time.Second
	shufflePDLeaderInterval      = flag.Int("shuffle-pd-leader-interval", 5, "second, the interval of shuffling pd leader")
	shufflePDLeaderCountPerRound = flag.Int("shuffle-pd-leader-per-round", 5, "how many time should we shuffle pd leader per-round")
	// So PD leader has enough time to make some operators.
	shufflePDLeaderRoundInterval = flag.Int("shuffle-pd-leader-round-interval", 5, "minute, the interval of rounds of shuffling pd leader")
)

func main() {
	client.Info("[shuffle] start...")
	flag.Parse()

	ctx, cancel := context.WithCancel(context.Background())
	cli := client.New(ctx, client.ModeOnline)

	sc := make(chan os.Signal, 1)
	signal.Notify(sc,
		syscall.SIGHUP,
		syscall.SIGINT,
		syscall.SIGTERM,
		syscall.SIGQUIT)
	go func() {
		sig := <-sc
		client.Infof("[shuffle] Got signal [%s] to exist.", sig)
		cancel()
		os.Exit(0)
	}()

	metricsAddr := cli.PrometheusAddr()
	if len(metricsAddr) > 0 {
		go util.PushPrometheus("shuffle", metricsAddr, defaultPushMetricsInterval)
	}

	cfg := arsenal.Config{
		PDAddrs:       cli.PDs(),
		ShuffleLeader: true,
		ShuffleRegion: true,

		ShufflePDLeader:      true,
		ShuffleInterval:      time.Duration(*shufflePDLeaderInterval) * time.Second,
		ShufflePerRound:      *shufflePDLeaderCountPerRound,
		ShuffleRoundInterval: time.Duration(*shufflePDLeaderRoundInterval) * time.Minute,
	}
	arsenal.PDShuffle(ctx, cfg)
}
