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 drop bool
	var init bool
	var port int
	var version bool
	var noscanip 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(&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.BoolVar(&noscanip, "noscanip", false, "Do not run scanip")

	flag.Parse()

	cfg.Switchs.Drop = drop
	cfg.Switchs.Init = init
	cfg.Switchs.Port = port
	cfg.Switchs.Version = version
	cfg.Switchs.NoScanIP = noscanip

	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.SocketChannel = "ipbl"
	cfg.Options.HideBanner = ipblsection.Key("hidebanner").MustBool(false)
	cfg.Options.Debug = ipblsection.Key("debug").MustBool(false)

	return nil
}

type Config struct {
	Db       *xorm.Engine
	DbParams struct {
		DbHostname string
		DbUsername string
		DbPassword string
		DbDatabase string
	}
	Options struct {
		Version       string
		HideBanner    bool
		SocketChannel string
		Debug         bool
	}
	Switchs struct {
		Port     int
		NoFeed   bool
		Drop     bool
		Init     bool
		Version  bool
		NoScanIP bool
	}
}
