/*
Copyright © 2021 da/net research group <danet.fbi.h-da.de>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors
   may be used to endorse or promote products derived from this software
   without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/

package cmd

import (
	"context"
	"fmt"
	"os"
	"path/filepath"

	"code.fbi.h-da.de/danet/gosdn/controller"
	"code.fbi.h-da.de/danet/gosdn/controller/config"
	log "github.com/sirupsen/logrus"
	"github.com/spf13/cobra"

	"github.com/spf13/viper"
)

var cfgFile string
var loglevel string
var socket string
var csbiOrchestrator string
var pluginRegistry string
var pluginFolder string
var security string

// rootCmd represents the base command when called without any subcommands.
var rootCmd = &cobra.Command{
	Use:   "gosdn",
	Short: "starts the gosdn controller",
	Long: `Starts the gosdn controller and listens on port 8080
for REST API calls.`,
	RunE: func(cmd *cobra.Command, args []string) error {
		ctx, cancel := context.WithCancel(context.Background())
		defer cancel()
		return controller.Run(ctx)
	},
}

// 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 {
		log.WithFields(log.Fields{}).Error(err)
		os.Exit(1)
	}
}

func init() {
	cobra.OnInitialize(initConfig)

	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is ./configs/gosdn.toml)")
	rootCmd.PersistentFlags().StringVarP(&loglevel, "log-level", "l", "", "log level 'debug' or 'trace'")

	rootCmd.Flags().StringVar(&socket, "socket", "", "port for the controllers gRPC northbound interface")
	rootCmd.Flags().StringVar(&csbiOrchestrator, "csbi-orchestrator", "", "csbi orchestrator address")
	rootCmd.Flags().StringVar(&pluginRegistry, "plugin-registry", "", "plugin registry address")
	rootCmd.Flags().StringVar(&pluginFolder, "plugin-folder", "", "folder holding all goSDN specific plugins")
	rootCmd.Flags().StringVarP(&security, "security", "s", "", "security level 'secure' or 'insecure'")
}

const (
	configHome string = "./configs"
	configName string = "gosdn"
	configType string = "toml"
)

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if cfgFile != "" {
		// Use config file from the flag.
		viper.SetConfigFile(cfgFile)
	} else {
		env := config.DetermineConfigEnvironment()

		log.Debugf("environment is %s\n", env)

		viper.AddConfigPath(configHome)
		viper.AddConfigPath("/usr/local/etc/gosdn/")
		viper.SetConfigType(configType)
		viper.SetConfigName(fmt.Sprintf("%s-%s", env, configName))
	}

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

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

	if err := viper.BindPFlags(rootCmd.Flags()); err != nil {
		log.Fatal(err)
	}

	// Set default configuration values
	viper.SetDefault("socket", ":55055")
	viper.SetDefault("csbi-orchestrator", "localhost:55056")
	viper.SetDefault("plugin-registry", "localhost:55057")
	viper.SetDefault("plugin-folder", "plugins")
	viper.SetDefault("security", "secure")
	viper.SetDefault("defaultJWTDuration", 24)

	ll := viper.GetString("GOSDN_LOG")
	if ll != "" {
		loglevel = ll
	}
	log.SetReportCaller(true)
	switch loglevel {
	case "trace":
		log.SetLevel(log.TraceLevel)
	case "debug":
		log.SetLevel(log.DebugLevel)
	default:
		log.SetLevel(log.InfoLevel)
		log.SetFormatter(&log.JSONFormatter{})
		log.SetReportCaller(false)
	}
	log.WithFields(viper.AllSettings()).Debug("current viper config")
}

func ensureFileSystemStoreExists(pathToFile string) error {
	emptyString := []byte("")
	// create folder if it does not exist
	if err := os.MkdirAll(configHome, 0777); err != nil {
		return err
	}
	// create file if it does not exist
	if err := os.WriteFile(pathToFile, emptyString, 0666); err != nil {
		log.Println(err)
		return err
	}

	return nil
}

func ensureViperConfigFileExists() {
	// Viper will crash if you call 'WriteConfig()' and the file does
	// not exists yet.
	// Therefore we handle this case here.
	// Inspired by //https://github.com/spf13/viper/issues/430#issuecomment-661945101
	configPath := filepath.Join(configHome, configName+"."+configType)

	if _, err := os.Stat(configPath); os.IsNotExist(err) {
		err := ensureFileSystemStoreExists(configPath)
		if err != nil {
			panic(err)
		}
	}
}
