package config

import (
	"encoding/hex"
	"fmt"
	"log"
	"strings"

	"github.com/denisbrodbeck/machineid"
	"gopkg.in/ini.v1"
)

type Config struct {
	ClusterID      string
	AddressPublic  string
	AddressPrivate string
	NodeID         string

	Manager    Manager
	AmqpURI    string
	EtcdURI    string
	LibvirtTLS bool
}

type Manager struct {
	Peers   []string
	TlsKey  string
	TlsCert string
	TlsCA   string
}

func New() (*Config, error) {
	c, err := ini.Load("/etc/deevirt/config.ini")
	if err != nil {
		log.Fatal(err)
	}

	id, err := machineid.ID()
	if err != nil {
		log.Fatal(err)
	}

	mID, _ := hex.DecodeString(id)
	libvirtTLS, _ := c.Section("libvirt").Key("tls").Bool()

	//Manager
	peers := strings.Split(c.Section("mgr").Key("peers").String(), ",")

	manager := &Manager{
		Peers: peers,
	}

	return &Config{
		ClusterID:      c.Section("").Key("id_cluster").String(),
		AddressPublic:  c.Section("").Key("ip_public").String(),
		AddressPrivate: c.Section("").Key("ip_private").String(),
		NodeID:         fmt.Sprintf("%x-%x-%x-%x-%x", mID[:4], mID[4:6], mID[6:8], mID[8:10], mID[10:]),

		Manager:    *manager,
		AmqpURI:    c.Section("broker").Key("uri").String(),
		EtcdURI:    c.Section("etcd").Key("uri").String(),
		LibvirtTLS: libvirtTLS,
	}, nil
}
