package cmd

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

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"github.com/tidbcloud/audit-ng/server"
)

// NewAuditServerCmd creates the server command
func NewAuditServerCmd() *cobra.Command {
	return &cobra.Command{
		Use:   "server",
		Short: "continue pushing log to remote object storage",
		RunE: func(cmd *cobra.Command, args []string) error {
			vp := viper.GetViper()
			ad, err := server.New(vp)
			if err != nil {
				return err
			}

			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
				fmt.Println("receive signal ", sig.String())
				ad.Shutdown(ctx, cancel)
			}()

			return ad.Run(ctx)
		},
	}
}

func init() {
	rootCmd.AddCommand(NewAuditServerCmd())
}
