main
1package cmd
2
3import (
4 "errors"
5 "fmt"
6 "os"
7
8 "github.com/bryfry/cfdns/internal/cf"
9 "github.com/bryfry/cfdns/internal/iplookup"
10 "github.com/spf13/cobra"
11)
12
13const (
14 _cfdnsEnvZoneName = "CFDNS_ZONE_NAME"
15 _cfdnsEnvSubdomainName = "CFDNS_SUBDOMAIN_NAME"
16 _cfdnsEnvAPIToken = "CFDNS_API_TOKEN"
17)
18
19var (
20 _envErrFmt = "required env variable %s not found or empty"
21 ErrZoneNameRequired = errors.New(fmt.Sprintf(_envErrFmt, _cfdnsEnvZoneName))
22 ErrSubdomainNameRequired = errors.New(fmt.Sprintf(_envErrFmt, _cfdnsEnvSubdomainName))
23 ErrAPITokenRequired = errors.New(fmt.Sprintf(_envErrFmt, _cfdnsEnvAPIToken))
24)
25
26func RootCmd() *cobra.Command {
27 root := &cobra.Command{
28 Use: "cfdns",
29 Short: "update cloudflare dns",
30 Version: "0.0.1",
31 Args: cobra.NoArgs,
32 SilenceUsage: true,
33 RunE: rootE,
34 }
35 return root
36}
37
38func rootE(cmd *cobra.Command, args []string) error {
39
40 zoneName, zoneNameExists := os.LookupEnv(_cfdnsEnvZoneName)
41 if !zoneNameExists || len(zoneName) == 0 {
42 return ErrZoneNameRequired
43 }
44 subdomainName, subdomainNameExists := os.LookupEnv(_cfdnsEnvSubdomainName)
45 if !subdomainNameExists || len(subdomainName) == 0 {
46 return ErrSubdomainNameRequired
47 }
48 apiToken, apiTokenExists := os.LookupEnv(_cfdnsEnvAPIToken)
49 if !apiTokenExists || len(apiToken) == 0 {
50 return ErrAPITokenRequired
51 }
52
53 ipDetails, err := iplookup.Discover()
54 if err != nil {
55 return err
56 }
57 fmt.Printf("External IP: %s\n", ipDetails.Address)
58 fmt.Printf("DNS Record Name: %s\n", subdomainName)
59
60 cfdns, err := cf.New(
61 zoneName,
62 subdomainName,
63 apiToken)
64 if err != nil {
65 return err
66 }
67
68 fmt.Printf("Current DNS Record IP: %s\n", cfdns.IP())
69 err = cfdns.SetIP(ipDetails.Address)
70 if err != nil {
71 return err
72 }
73 fmt.Printf("Updated DNS Record IP: %s\n", cfdns.IP())
74 return nil
75}