package cmd

// DCSO FEVER
// Copyright (c) 2018, 2021, DCSO GmbH

import (
	"fmt"
	"os"

	homedir "github.com/mitchellh/go-homedir"
	log "github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var cfgFile string

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
	Use:   "fever",
	Short: "fast, extensible and flexible event router",
	Long: `FEVER is a fast execution engine for processing, aggregation and
reporting components that act on Suricata's EVE output.`,
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func init() {
	cobra.OnInitialize(initConfig)

	// Here you will define your flags and configuration settings.
	// Cobra supports persistent flags, which, if defined here,
	// will be global for your application.
	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.fever.yaml)")

	// Management server options
	rootCmd.PersistentFlags().StringP("mgmt-socket", "", "/tmp/fever-mgmt.sock", "Socket path for management server")
	viper.BindPFlag("mgmt.socket", rootCmd.PersistentFlags().Lookup("mgmt-socket"))
	rootCmd.PersistentFlags().StringP("mgmt-host", "", "", "hostname:port definition for management server")
	viper.BindPFlag("mgmt.host", rootCmd.PersistentFlags().Lookup("mgmt-host"))
	rootCmd.PersistentFlags().StringP("mgmt-network", "", "tcp", "network (tcp/udp) definition for management server")
	viper.BindPFlag("mgmt.network", rootCmd.PersistentFlags().Lookup("mgmt-network"))
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if cfgFile != "" {
		// Use config file from the flag.
		viper.SetConfigFile(cfgFile)
	} else {
		// Find home directory.
		home, err := homedir.Dir()
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

		// Search config in home directory with name ".fever" (without extension).
		viper.AddConfigPath(home)
		viper.SetConfigName(".fever")
	}

	viper.AutomaticEnv() // read in environment variables that match

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err == nil {
		log.Infof("Using config file: %s", viper.ConfigFileUsed())
	}
}
