Skip to content

Commit

Permalink
Upgrade the application to Systemd service
Browse files Browse the repository at this point in the history
  • Loading branch information
Praveen Premaratne committed Apr 23, 2022
1 parent 43c34d4 commit 18aa17a
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 3 deletions.
23 changes: 23 additions & 0 deletions dyndns.service
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
[Unit]
Description=DynDNS
After=network.target network-online.target
StartLimitIntervalSec=60s
StartLimitBurst=3

[Service]
Environment=CF_token=''
Environment=Domain=''
Environment=Subdomain=''
Environment=CF_proxy_disabled=1
ExecStart=/usr/local/bin/DynDNS
Type=simple
User=root
Group=root
Restart=always
RestartSec=5
SyslogIdentifier=DynDNS
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
43 changes: 40 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,53 +3,67 @@ package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"github.com/praveenprem/dyndns/cloudflare"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)

type ipv4 struct {
IP string `json:"ip"`
}

func main() {
func logger(msg interface{}) {
log.Printf("%#v", msg)
}

func runner() {
defer func() {
if err := recover(); err != nil {
fmt.Println(err)
os.Exit(2)
}
}()

logger("Initiating IP update")

logger("Cloudflare DNS host found")
var cf = cloudflare.Cloudflare{}
cf.Proxied = true

if token, ok := os.LookupEnv("CF_token"); !ok {
panic(errors.New("cloudflare Token not set"))
} else {
logger("Cloudflare token found")
cf.Token = token
}

if domain, ok := os.LookupEnv("Domain"); !ok {
panic(errors.New("domain name not set"))
} else {
logger("Domain: " + domain)
cf.Domain = domain
}

if hostname, ok := os.LookupEnv("Subdomain"); !ok {
log.Print(hostname)
logger(hostname)
panic(errors.New("subdomain not set"))
} else {
cf.Hostname = hostname
}

if _, ok := os.LookupEnv("CF_proxy_disabled"); !ok {
log.Printf("CF_proxy_disabled not set")
logger("CF_proxy_disabled not set")
} else {
cf.Proxied = false
}

logger("Fetching new IP address")
ip := new(ipv4)

client := new(http.Client)
Expand All @@ -68,9 +82,32 @@ func main() {
}
}

logger(ip.IP)

cf.IpAddress = ip.IP

logger("Updating DNS record")
if err := cf.UpdateRecordSet(); err != nil {
panic(err)
}

logger("Update completed")
}

func main() {
interval := flag.Int64("freq", 2, "IP update frequency in hours. Default 2h")
flag.Parse()

sigs := make(chan os.Signal, 1)
signal.Notify(sigs, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
go func() {
s := <-sigs
log.Printf("RECEIVED SIGNAL: %s", s)
os.Exit(1)
}()

for {
runner()
time.Sleep(time.Hour * time.Duration(*interval))
}
}

0 comments on commit 18aa17a

Please sign in to comment.