package main

import (
	"context"
	"flag"
	"fmt"
	"os"
	"os/signal"
	"syscall"

	"github.com/Kong/go-pdk/server"
	"github.com/spf13/viper"

	"github.com/tidbcloud/audit-kong/log"
	"github.com/tidbcloud/audit-kong/logger"
	"github.com/tidbcloud/audit-kong/plugin"
)

func main() {
	var cfgFile string
	flag.StringVar(&cfgFile, "config", "/etc/kong/audit/config.yaml", "config file path")
	flag.Parse()

	// NOTE: Kong use the `-dump` flag to get the plugin info table
	// if the `-dump` flag is set, we can't ouput other things to stdout.
	// otherwise, Kong can't parse the output correctly.
	needStart := true
	if dump := flag.Lookup("dump"); dump != nil && dump.Value.String() == "true" {
		needStart = false
	}

	if needStart {
		viper.SetConfigFile(cfgFile)
		viper.AutomaticEnv()
		if err := viper.ReadInConfig(); err != nil {
			fmt.Fprintln(os.Stderr, "Error reading config file:", err)
		} else {
			fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
		}
		viper.WatchConfig()

		ctx, cancel := context.WithCancel(context.Background())
		defer cancel()
		sc := make(chan os.Signal, 1)
		signal.Notify(sc,
			syscall.SIGHUP,
			syscall.SIGINT,
			syscall.SIGTERM,
			syscall.SIGQUIT,
		)
		go func() {
			sig := <-sc
			log.Infof("receive signal %s", sig.String())
			cancel()
		}()
		logger.GetLogger().Run(ctx)
		log.Infof("Starting audit-kong plugin server...")
	}

	err := server.StartServer(plugin.NewPlugin, "0.1.0", 10)
	if err != nil {
		log.Errorf("Failed to start audit-kong plugin server: %v", err)
	}
}
