package main

import (
	"log"
	"net"
	"net/http"
	"os"
	"strings"
)

func main() {
	addr, port := env("API_REGISTRY_ADDR", "api-registry"), env("API_REGISTRY_PORT", "8501")
	regUrl := "https://" + addr + ":" + port + "/v1/agent/service/register?replace-existing-checks=true"
	regData, err := os.ReadFile("/.app.config")
	if err != nil {
		log.Fatal(err)
	}

	ip := getIP()
	strRegData := string(regData)
	strRegData = strings.Replace(strRegData, "__IP__", ip, -1)

	req, err := http.NewRequest(http.MethodPut, regUrl, strings.NewReader(strRegData))
	if err != nil {
		log.Fatal(err)
	}

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Printf(err.Error())
		log.Fatal(err)
	}
	var respBody []byte
	resp.Body.Read(respBody)

	log.Printf("Successfully registered")
}

func env(name, def string) string {
	val := os.Getenv(name)

	if len(val) == 0 {
		return def
	}

	return val
}

func getIP() string {
	host, _ := os.Hostname()
	ips, _ := net.LookupIP(host)
	for _, ip := range ips {
		return ip.String()
	}

	return host
}
