package main

import (
	"os"
	"time"

	"dnsupdater/app"

	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
)

func main() {
	log.Logger = log.Output(zerolog.ConsoleWriter{
		Out:        os.Stderr,
		TimeFormat: time.RFC3339,
	})

	config, err := app.LoadConfig("config.yml")
	if err != nil {
		log.Fatal().Err(err).Msg("Failed to load config")
	}

	app, err := app.NewApp(config)
	if err != nil {
		log.Fatal().Err(err).Msg("Failed to initialize application")
	}

	for service_name, domains := range config.Updates {

		log.Info().Str("service", service_name).Msg("Begin update for service")

		// Get service
		service := app.ProviderManager.Get(service_name)

		for domain, records := range domains {
			for name, data := range records {

				logger := log.With().
					Str("service", service_name).
					Str("domain", domain).
					Str("record", name).
					Str("interface", data).
					Logger()

				ip, err := app.GetIP(data)
				if err != nil {
					logger.Error().Err(err).Msg("Failed to fetch ip")
					continue
				}

				logger = logger.With().IPAddr("ip", ip).Logger()

				err = service.Update(domain, name, ip)
				if err != nil {
					logger.Error().Err(err).Msg("Failed to update record")
				} else {
					logger.Info().Msg("Record updated")
				}
			}
		}

	}
}
