package main

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

	"github.com/juju/errors"
	"github.com/ngaut/log"
	"github.com/pingcap/schrodinger/buildbot/config"
	"github.com/pingcap/schrodinger/buildbot/core"
	"github.com/pingcap/schrodinger/pkg/storage"
	"github.com/pingcap/schrodinger/util"
	"golang.org/x/sync/errgroup"
)

var (
	cfg         *config.Config
	configFile  string
	version     bool
	storeConfig storage.Config
	pprofPort   int
)

func init() {
	flag.StringVar(&configFile, "c", "", "config file address")
	flag.BoolVar(&version, "version", false, "build bot version")
	flag.IntVar(&pprofPort, "pprof", 10080, "the port of pprof")
}

func setGlobalVars() {
	storeConfig.Driver = cfg.Storage.Driver
	storeConfig.Datasource = cfg.Storage.Datasource
	storeConfig.MaxIdleConns = cfg.Storage.MaxIdleConns
}

func main() {
	flag.Parse()

	if version {
		util.PrintInfo()
		return
	}

	loadConfig()
	setGlobalVars()

	store, err := storage.NewStorage(storeConfig)
	if err != nil {
		log.Fatal(errors.ErrorStack(err))
	}

	mgr := core.NewBuildManager(store, cfg.BaseConfig)
	if err := mgr.Recover(); err != nil {
		log.Fatal(errors.ErrorStack(err))
	}

	sc := make(chan os.Signal, 1)
	signal.Notify(sc,
		syscall.SIGHUP,
		syscall.SIGINT,
		syscall.SIGTERM,
		syscall.SIGQUIT)

	ctx, cancel := context.WithCancel(context.Background())

	go func() {
		sig := <-sc
		cancel()

		log.Infof("Got signal [%d] to exit", sig)
	}()

	g := errgroup.Group{}
	g.Go(func() error {
		return mgr.Run(ctx)
	})

	log.Info("buildbot serve is running")

	go func() {
		log.Info(http.ListenAndServe(fmt.Sprintf("0.0.0.0:%d", pprofPort), nil))
	}()

	if err := g.Wait(); err != nil {
		log.Error(errors.ErrorStack(err))
	}
}

func loadConfig() {
	cfg = config.GetBuildConfig()

	if configFile != "" {
		if err := cfg.Load(configFile); err != nil {
			log.Fatalf(errors.ErrorStack(err))
		}
	}
}
