// SPDX-FileCopyrightText: 2021 Luke Granger-Brown <depot@lukegb.com>
//
// SPDX-License-Identifier: Apache-2.0

package cmd

import (
	"log"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var (
	cfgFile string

	rootCmd = &cobra.Command{
		Use:   "fup",
		Short: "fup is a minimalistic file server.",
		Long:  "fup handles uploads and downloads of content.",
	}
)

func bucketURL() string { return viper.GetString("storage.bucketURL") }

func Execute() error {
	return rootCmd.Execute()
}

func init() {
	cobra.OnInitialize(initConfig)

	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file")
	rootCmd.PersistentFlags().String("bucket-url", "mem://", "gocloud.dev-compatible URL to use for file storage")
	viper.BindPFlag("storage.bucketURL", rootCmd.PersistentFlags().Lookup("bucket-url"))
	viper.SetDefault("storage.bucketURL", "mem://")
}

func initConfig() {
	if cfgFile != "" {
		viper.SetConfigFile(cfgFile)
	}

	viper.SetEnvPrefix("fup")
	viper.AutomaticEnv()

	if err := viper.ReadInConfig(); err == nil {
		log.Printf("Using config file: %v", viper.ConfigFileUsed())
	}
}