package main

import (
	"fmt"
	"os"
	"strings"

	"git.agecem.com/bottin/bottin/v10/pkg/bottin"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

type Config struct {
	// Bottin holds a client config to contact a bottin API server
	// Cannot be set using environment variables
	Bottin bottin.APIClientConfig

	DB struct {
		Database string
		Host     string
		Password string
		Port     int
		SSLMode  string
		Username string
	}

	// TLS holds options for TLS / SSL / HTTPS
	TLS struct {
		// Cert holds the public certificate (or path to a file containing one) for user interface TLS
		Cert string

		// Key holds the private key (or path to a file containing one) for user interface TLS
		Key string

		// Enabled holds the TLS activation state
		Enabled bool
	}

	// Credentials holds username-password pairs for basic authentication
	Credentials map[string]string

	// Port holds the port on which to expose the user interface
	Port int
}

func ParseConfig() (cfg Config, err error) {
	return cfg, viper.Unmarshal(&cfg)
}

var cfgFile string

// 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 := os.UserHomeDir()
		cobra.CheckErr(err)

		// Search config in home directory with name ".bottin.agendas" (without extension).
		viper.AddConfigPath(home)
		viper.SetConfigType("yaml")
		viper.SetConfigName(".bottin.agendas")
	}

	// Read in env, will find matching viper bindings in flag.go [BindFlags]
	viper.SetEnvPrefix("AGENDAS")
	viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
	viper.AutomaticEnv() // read in environment variables that match

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err == nil {
		fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
	}
}

func init() {
	cobra.OnInitialize(initConfig)
}

// 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() {
	err := rootCmd.Execute()
	if err != nil {
		os.Exit(1)
	}
}