package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"net/http"
	_ "net/http/pprof"
	"os"
	"os/signal"
	"syscall"

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

func main() {
	client.Info("[tibug-52] start...")
	flag.Parse()

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

	// monitoring system exit message
	sc := make(chan os.Signal, 1)
	signal.Notify(sc,
		syscall.SIGHUP,
		syscall.SIGINT,
		syscall.SIGTERM,
		syscall.SIGQUIT)

	go func() {
		sig := <-sc
		client.Infof("[tibug-52] Got signal [%s] to exist.", sig)
		cancel()
		os.Exit(0)
	}()

	pdAddr := cli.PdService()
	if isOptionDefaultOn(pdAddr) {
		// fail
		client.Fatalf("[tibug-52] the 'strictly-match-label' option should be false, but it is true")
	} else {
		client.Infof("[tibug-52] the 'strictly-match-label' option is false, ok")
	}
}

// check if strictly-match-label option is true by default
func isOptionDefaultOn(pdAddr string) bool {
	uri := fmt.Sprintf("http://%s/pd/api/v1/config/replicate", pdAddr)
	resp, err := http.Get(uri)
	if err != nil {
		client.Fatalf("[tibug-52] send request to pd failed")
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		client.Fatalf("[tibug-52] PD response status code is %d, expect 200", resp.StatusCode)
	}
	var replication map[string]interface{}
	if err := json.NewDecoder(resp.Body).Decode(&replication); err != nil {
		client.Fatalf("[tibug-52] can't decode PD response body")
	}
	val, ok := replication["strictly-match-label"]
	if !ok {
		client.Infof("[tibug-52] no config option strictly-match-label.")
		return false
	}
	return val.(string) != "false"
}
