// Copyright 2016 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"
	"strings"
	"syscall"

	"github.com/juju/errors"
	"github.com/ngaut/log"
	"github.com/pingcap/tidb-enterprise-tools/pkg/utils"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

func main() {
	cfg := NewConfig()
	err := cfg.Parse(os.Args[1:])
	switch errors.Cause(err) {
	case nil:
	case flag.ErrHelp:
		os.Exit(0)
	default:
		log.Errorf("parse cmd flags err %s\n", err)
		os.Exit(2)
	}

	log.SetLevelByString(strings.ToLower(cfg.LogLevel))
	if len(cfg.LogFile) > 0 {
		log.SetOutputByName(cfg.LogFile)
		log.SetHighlighting(false)
	}

	utils.PrintInfo("loader", func() {
		log.Infof("config: %s", cfg)
	})

	loader, err := NewLoader(cfg)
	if err != nil {
		log.Fatalf("[loader] initialize loader error %s", 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())
	defer cancel()

	go func() {
		sig := <-sc
		log.Infof("Got signal [%v] to exit.", sig)
		loader.Close(cancel)
	}()

	go func() {
		http.Handle("/metrics", promhttp.Handler())
		err1 := http.ListenAndServe(cfg.StatusAddr, nil)
		if err1 != nil {
			log.Fatal(err1)
		}
	}()

	if err := loader.Restore(ctx); err != nil {
		log.Fatal(errors.ErrorStack(err))
	}
	loader.Close(cancel)

	log.Info("loader stopped and exits")
}
