package config

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

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

type Config struct {
	ClusterID  string
	NodeID     string
	AmqpURI    string
	EtcdURI    string
	LibvirtTLS bool
}

func NewConfig() (*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()

	return &Config{
		ClusterID:  c.Section("").Key("id").String(),
		NodeID:     fmt.Sprintf("%x-%x-%x-%x-%x", mID[:4], mID[4:6], mID[6:8], mID[8:10], mID[10:]),
		AmqpURI:    c.Section("broker").Key("uri").String(),
		EtcdURI:    c.Section("etcd").Key("uri").String(),
		LibvirtTLS: libvirtTLS,
	}, nil
}
