// Copyright 2019 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 main

import (
	"context"
	"flag"
	"net/http"
	_ "net/http/pprof"
	"os"
	"os/signal"
	"syscall"

	"github.com/pingcap/schrodinger-test/randtxn/txn"
	client "github.com/pingcap/schrodinger/pkg/test_client"
)

var (
	mysqlVersion string
	dbName       string
	maxTxnSize   int
)

func init() {
	flag.StringVar(&mysqlVersion, "mysql-version", "5.7", "mysql version")
	flag.IntVar(&maxTxnSize, "txn_size", 50, "max statement size in the transaction")
	flag.StringVar(&dbName, "db", "test", "database name")
}

func main() {
	flag.Parse()
	client.Info("rand txn test start...")

	go func() {
		client.Info(http.ListenAndServe("localhost:6060", nil))
	}()

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

	setUpSignalHandle(cancel)

	mysql, err := cli.CreateMysql(mysqlVersion, 0)
	if err != nil {
		client.Fatalf("create mysql error %v", client.ErrorStack(err))
	}
	client.Info("set up mysql success")

	tidbAddr := cli.TiDBService()
	ts := txn.NewTestSuit(tidbAddr, "", mysql.Host+":3306", "", dbName)
	ts.PrepareTables()
	ts.StartTest(maxTxnSize)
}

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

}
