package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "os"
    "time"
)

type Config struct {
    URL           string `json:"url"`
    IntervalMins  int    `json:"interval_minutes"`
}

// read config.json
func loadConfig(path string) (*Config, error) {
    file, err := ioutil.ReadFile(path)
    if err != nil {
        return nil, err
    }
    var cfg Config
    err = json.Unmarshal(file, &cfg)
    if err != nil {
        return nil, err
    }
    return &cfg, nil
}

func updateDDNS(url string) {
    resp, err := http.Get(url)
    if err != nil {
        fmt.Println("Error calling DDNS URL:", err)
        return
    }
    defer resp.Body.Close()

    if resp.StatusCode == http.StatusOK {
        fmt.Println(time.Now(), "DDNS updated successfully")
    } else {
        fmt.Println(time.Now(), "Failed to update DDNS, status code:", resp.StatusCode)
    }
}

func main() {
    cfg, err := loadConfig("config.json")
    if err != nil {
        fmt.Println("Failed to load config:", err)
        os.Exit(1)
    }

    ticker := time.NewTicker(time.Duration(cfg.IntervalMins) * time.Minute)
    defer ticker.Stop()

    // run immediately once
    updateDDNS(cfg.URL)

    for range ticker.C {
        updateDDNS(cfg.URL)
    }
}
