package clinit

import (
	"fmt"
	"os"
	"strings"
	"time"

	"go.etcd.io/etcd/client"
)

var etcdClient client.Client

func InitEtcd(etcdaddrs []string) {
	endpoints := []string{}
	for _, addr := range etcdaddrs {
		if strings.HasPrefix(addr, "http://") {
			endpoints = append(endpoints, addr)
		} else {
			endpoints = append(endpoints, fmt.Sprintf("http://%s", addr))
		}
	}
	cli, err := client.New(client.Config{
		Endpoints:               endpoints,
		Transport:               client.DefaultTransport,
		HeaderTimeoutPerRequest: 5 * time.Second,
	})
	if err != nil {
		fmt.Printf("new etcd client failed. error:%s\n", err)
		os.Exit(1)
	}
	etcdClient = cli
}

func GetEtcdClient() client.Client {
	return etcdClient
}
