diff --git a/main.go b/main.go index f28f469..a254274 100644 --- a/main.go +++ b/main.go @@ -1,21 +1,46 @@ package main import ( - "log" + "flag" + "fmt" "os" "github.com/jimeh/cloudflare-dyndns/updater" ) func main() { - var email = os.Getenv("CF_EMAIL") - var apiKey = os.Getenv("CF_API") - var host = os.Getenv("CF_HOST") + var email string + var apiKey string + var host string + + flag.StringVar( + &email, "email", os.Getenv("CF_EMAIL"), + "Cloudflare email account. Can be specified via CF_EMAIL env var.", + ) + flag.StringVar( + &apiKey, "apikey", os.Getenv("CF_APIKEY"), + "Cloudflare API key. Can be specified via CF_APIKEY env var.", + ) + flag.StringVar( + &host, "host", os.Getenv("CF_HOST"), + "DNS entry to update. Can be specified via CF_HOST env var.", + ) + + flag.Parse() + + if email == "" || apiKey == "" || host == "" { + fmt.Println("usage: cloudflare-dyndns \n\noptions:") + flag.PrintDefaults() + os.Exit(1) + } updater := updater.New(email, apiKey) - err := updater.Update(host) + stop, err := updater.UpdateLoop(host) if err != nil { - log.Fatal(err) + fmt.Printf("ERROR: %s\n", err.Error()) + os.Exit(1) } + + <-stop // wait forever } diff --git a/updater/updater.go b/updater/updater.go index 72b9e7b..63a6d32 100644 --- a/updater/updater.go +++ b/updater/updater.go @@ -38,25 +38,51 @@ type Updater struct { Interval int } -// Update performs a the full update sequence. -func (u *Updater) Update(host string) error { +// UpdateLoop performs a the full update sequence. +func (u *Updater) UpdateLoop(host string) (<-chan bool, error) { + stop := make(chan bool, 1) + fmt.Printf("Looking up record for %s...\n", host) + record, err := u.RecordByHost(host) + if err != nil { + return stop, err + } + + fmt.Printf("Found %s (Zone: %s)\n", record.Name, record.ZoneName) + go func() { + fmt.Printf("Starting IP check (repeats every %d seconds)\n", u.Interval) + + _, err = u.UpdateRecord(record) + if err != nil { + fmt.Printf("ERROR: %s\n", err.Error()) + } + + for { + select { + case <-stop: + close(stop) + return + case <-time.After(time.Second * time.Duration(u.Interval)): + _, err = u.UpdateRecord(record) + if err != nil { + fmt.Printf("ERROR: %s\n", err.Error()) + } + } + } + }() + + return stop, nil +} + +// Update performs a single update +func (u *Updater) Update(host string) error { record, err := u.RecordByHost(host) if err != nil { return err } - fmt.Printf("Found %s (%s)\n", record.Name, record.ID) - fmt.Printf("Starting IP check (repeats every %d seconds)\n", u.Interval) - for { - record, err = u.UpdateRecord(record) - if err != nil { - fmt.Printf("ERROR: %s\n", err.Error()) - fmt.Printf("Retrying in %d seconds...", u.Interval) - } - - time.Sleep(time.Duration(u.Interval) * time.Second) - } + _, err = u.UpdateRecord(record) + return err } // UpdateRecord updates a cloudflare.DNSRecord.