package main

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

	"github.com/pingcap/schrodinger/pkg/test_client"
	"golang.org/x/net/context"
)

var (
	mode            string
	component       string
	interval        time.Duration
	recoverInterval time.Duration
	notifyDDL       string
)

func init() {
	flag.StringVar(&mode, "mode", "random", "which mode will use, random kill or selected")
	flag.DurationVar(&interval, "interval", 10*time.Minute, "what interval will kill a node")
	flag.StringVar(&component, "component", "all", "which component whill use")
	flag.DurationVar(&recoverInterval, "recover-interval", 25*time.Second, "interval between recover")
	flag.StringVar(&notifyDDL, "notify-ddl", "", "notify ddl name")
}

func main() {
	flag.Parse()

	client.Info("[nemesis] start...")

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

	cfg := &config{
		mode:            mode,
		component:       component,
		notifyDDL:       notifyDDL,
		interval:        interval,
		recoverInterval: recoverInterval,
	}

	nemesis, err := createNemesis(ctx, cfg, cli)
	if err != nil {
		client.Fatalf("run nemesis failed %+v", err)
	}

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

	err = nemesis.Run()
	if err != nil {
		client.Fatalf("run nemesis failed %+v", err)
	}
}
