package main

import (
	"bytes"

	"github.com/docopt/docopt.go"
	"github.com/spf13/viper"
	"sour.is/x/toolbox/log"
	"sour.is/x/toolbox/log/event"
	_ "sour.is/x/toolbox/stats"
)

var (
	// AppVersion Application Version Number
	AppVersion string

	// AppBuild Application Build Number
	AppBuild string
)

// AppName name of the application
var AppName = "Paste API"

// AppUsage displays runtime options
var AppUsage = `Paste API

Usage:
  paste version
  paste [ -v | -vv ] serve

Options:
  -v                                             Log info to console.
  -vv                                            Log debug to console.
  -l <ListenAddress>, --listen=<ListenAddress>   Address to listen on.
  -c <ConfigDir>, --config=<ConfigDir>           Set Config Directory.

Config:
  The config file is read from the following locations:
    - <ConfigDir>
    - /etc/opt/sour.is/paste/
    - Working Directory
`
var defaultConfig = `
[http]
listen   = ":9010"

[module.paste]
random = "4096"
store = "data/"
`

var args map[string]interface{}

func init() {
	var err error

	viper.Set("app.name", AppName)
	viper.SetDefault("app.version", "VERSION")
	if AppVersion != "" {
		viper.Set("app.version", AppVersion)
	}
	viper.SetDefault("app.build", "SNAPSHOT")
	if AppBuild != "" {
		viper.Set("app.build", AppBuild)
	}

	if args, err = docopt.ParseDoc(AppUsage); err != nil {
		log.Fatal(err)
	}

	if args["-v"].(int) == 1 {
		log.SetVerbose(event.VerbInfo)
		log.Info("Verbose Logging.")
	}
	if args["-v"].(int) == 2 {
		log.SetVerbose(event.VerbDebug)
		log.Debug("Very Verbose Logging.")
	}

	log.Printf("%s (%s %s)\n",
		viper.GetString("app.name"),
		viper.GetString("app.version"),
		viper.GetString("app.build"))

	if args["serve"] == true {

		viper.SetConfigName("config")
		if args["--config"] != nil {
			viper.AddConfigPath(args["--config"].(string))
		}

		viper.AddConfigPath("/etc/opt/sour.is/paste/")
		viper.AddConfigPath(".")

		viper.SetConfigType("toml")
		viper.ReadConfig(bytes.NewBuffer([]byte(defaultConfig)))

		err = viper.MergeInConfig()
		if err != nil { // Handle errors reading the config file
			log.Warningf("config file not found: %s \n", err)
		} else {
			log.Notice("Read config from: ", viper.ConfigFileUsed())
		}

		if args["--listen"] != nil {
			viper.Set("http.listen", args["--listen"].(string))
		}
	}
}
