package main

import (
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"log"
	"net"
	"os"
	"time"
)

func getLocalIP() (string, error) {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return "", err
	}
	for _, addr := range addrs {
		if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				return ipnet.IP.String(), nil
			}
		}
	}
	return "", fmt.Errorf("no IP address found")
}

func publishIp(client mqtt.Client, topic string) {
	log.Printf("Publishing IP")
	ip, err := getLocalIP()
	if err != nil {
		log.Printf("Error getting IP address: %v\n", err)
		return
	}
	token := client.Publish(topic, 0, true, ip)
	token.Wait()
	if token.Error() != nil {
		log.Printf("Error publishing IP address: %v\n", token.Error())
	} else {
		log.Printf("Published IP address: %s\n", ip)
	}
}

func main() {
	broker := "tcp://mqtt.seeseepuff.be:1883"
	topic := "host/" + os.Getenv("SPIDER_HOSTNAME")

	opts := mqtt.NewClientOptions()
	opts.AddBroker(broker)
	opts.SetClientID("spider-host-client")
	client := mqtt.NewClient(opts)

	token := client.Connect()
	token.Wait()
	if token.Error() != nil {
		log.Fatalf("Error connecting to MQTT broker: %v\n", token.Error())
	}

	ticker := time.NewTicker(60 * time.Second)
	defer ticker.Stop()

	publishIp(client, topic)
	for {
		select {
		case <-ticker.C:
			publishIp(client, topic)
		}
	}
}
