package main

import (
	"context"
	"flag"
	"fmt"
	"github.com/pingcap/schrodinger/pkg/test_client"
	"math/rand"
	"os"
	"os/exec"
	"os/signal"
	"syscall"
	"time"
)

var (
	modChangeInterval = flag.Duration("interval", time.Hour, "Interval to change titan run-mode")
)

func changeMod(nodes []string) {
	oldMod := "kNormal"
	for {
		time.Sleep(*modChangeInterval)
		var mod string
		switch rand.Int() % 3 {
		case 0:
			mod = "kNormal"
		case 1:
			mod = "kReadOnly"
		case 2:
			mod = "kFallback"
		}
		for _, n := range nodes {
			cmd := exec.Command("sh","-c",fmt.Sprintf("/tikv-ctl --host %s"+
				" modify-tikv-config -m kvdb -n default.blob_run_mode -v \"%s\"", n, mod))
			err := cmd.Run()
			if err != nil {
				client.Fatalf("[Titandb_downgrade] Change nde %s blob_run_mode to %s, error %v",
					n, mod, client.ErrorStack(err))
			}
			client.Info("[Titandb_downgrade] Switch node %s run-mode from %s to %s",n, oldMod, mod)
		}
		oldMod = mod
	}
}

func main() {
	flag.Parse()
	client.Info("[Titandb_downgrade] Start TiKV cluster...")
	ctx, cancel := context.WithCancel(context.Background())

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

	cli := client.New(ctx, client.ModeOnline)
	tikvs := cli.TiKVs()
	changeMod(tikvs)
}
