package config

import (
	"flag"

	"git.paulbsd.com/paulbsd/ipbl/utils"
	"gopkg.in/ini.v1"
	"xorm.io/xorm"
)

func (cfg *Config) GetConfig() error {
	var configfile string
	var debug bool
	var drop bool
	var init bool
	var port int
	var version bool

	flag.Usage = utils.Usage

	flag.StringVar(&configfile, "configfile", "ipbl.ini", "Configuration file to use with ipbl section")
	flag.IntVar(&port, "port", 8099, "Web service port to use")
	flag.BoolVar(&debug, "debug", false, "If debug logging must be enabled")
	flag.BoolVar(&drop, "drop", false, "If dropping tables must occur")
	flag.BoolVar(&init, "init", false, "If init of database must be done")
	flag.BoolVar(&version, "version", false, "Show version")

	flag.Parse()

	cfg.Switchs.Debug = debug
	cfg.Switchs.Drop = drop
	cfg.Switchs.Init = init
	cfg.Switchs.Port = port
	cfg.Switchs.Version = version

	var inicfg, err = ini.Load(configfile)
	if err != nil {
		return err
	}

	var ipblsection = inicfg.Section("ipbl")

	cfg.DbParams.DbHostname = ipblsection.Key("hostname").MustString("localhost")
	cfg.DbParams.DbUsername = ipblsection.Key("username").MustString("username")
	cfg.DbParams.DbPassword = ipblsection.Key("password").MustString("password")
	cfg.DbParams.DbDatabase = ipblsection.Key("database").MustString("database")

	cfg.Options.ZMQChannel = "ipbl"
	cfg.Options.HideBanner = ipblsection.Key("hidebanner").MustBool(false)

	return nil
}

type Config struct {
	Db       *xorm.Engine `json:"-"`
	DbParams struct {
		DbHostname string `json:"dbhostname"`
		DbUsername string `json:"dbusername"`
		DbPassword string `json:"dbpassword"`
		DbDatabase string `json:"dbdatabase"`
	} `json:"dbparams"`
	Options struct {
		Version    string `json:"version"`
		HideBanner bool   `json:"hidebanner"`
		ZMQChannel string `json:"zmqchannel"`
	} `json:"-"`
	Switchs struct {
		Port    int  `json:"port"`
		NoFeed  bool `json:"nofeed"`
		Debug   bool `json:"debug"`
		Drop    bool `json:"drop"`
		Init    bool `json:"init"`
		Version bool `json:"version"`
	} `json:"-"`
}
