-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
264 lines (220 loc) · 4.92 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package main
import (
"bytes"
"encoding/gob"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
)
type Secrets struct {
Key string `json:"apikey"`
Secret string `json:"secretapikey"`
}
type Record struct {
ID string `json:"id,omitempty"`
Name string `json:"name"`
RecordType string `json:"type"`
Content string `json:"content"`
TTL string `json:"ttl"`
}
type IPResp struct {
Status string `json:"status"`
IP string `json:"yourIp"`
}
type RecordsResp struct {
Status string `json:"status"`
Records []Record `json:"records"`
}
type EditRecordReq struct {
Key string `json:"apikey"`
Secret string `json:"secretapikey"`
Name string `json:"name"`
RecordType string `json:"type"`
Content string `json:"content"`
TTL string `json:"ttl"`
}
var secrets Secrets
var BASE_PATH = "https://porkbun.com/api/json/v3"
var filepath = os.ExpandEnv("$HOME") + "/.pddc"
var domain string
var currentIP string
func init() {
loadSecrets()
}
func main() {
if len(os.Args) < 2 {
log.Fatalln("Unable to parse domain argument")
}
domain := os.Args[1]
if domain == "ping" {
ip, err := getIP()
if err != nil {
log.Fatalln("ping failed: ", err)
}
fmt.Printf("your ip is %s", ip)
} else {
ip, err := getIP()
if err != nil {
fmt.Println(err)
}
prevIP, err := getPrevIP()
if err != nil {
fmt.Println(err)
}
if ip != prevIP {
tempRecords := fetchRecords()
records := filterRecords(ip, tempRecords)
if len(records) > 0 {
updateRecords(records)
}
}
}
}
func fetchRecords() []Record {
path := "/dns/retrieve/" + domain
jsonBody, err := json.Marshal(secrets)
if err != nil {
fmt.Println(err)
}
resp := postRequest(path, jsonBody)
var rec []Record
if resp.StatusCode == http.StatusOK {
var jsonResp RecordsResp
json.NewDecoder(resp.Body).Decode(&jsonResp)
return jsonResp.Records
} else {
log.Fatalf("Could not fetch records, status %d", resp.StatusCode)
return rec
}
}
func getIP() (string, error) {
jsonBody, err := json.Marshal(secrets)
if err != nil {
fmt.Println(err)
}
resp := postRequest("/ping", jsonBody)
if resp.StatusCode == http.StatusOK {
var jsonResp IPResp
json.NewDecoder(resp.Body).Decode(&jsonResp)
currentIP = jsonResp.IP
return jsonResp.IP, nil
} else {
return "", errors.New(fmt.Sprintf("API request returned status: %d", resp.StatusCode))
}
}
func updateRecords(records []Record) {
for _, rec := range records {
updateRecord(rec)
}
updateIP(currentIP)
}
func createEditRecordReq(record Record) EditRecordReq {
var eRec EditRecordReq
eRec.Key = secrets.Key
eRec.Secret = secrets.Secret
eRec.Content = record.Content
eRec.RecordType = record.RecordType
eRec.Name = record.Name
eRec.TTL = record.TTL
return eRec
}
func updateRecord(record Record) {
rec := createEditRecordReq(record)
jsonBody, err := json.Marshal(rec)
if err != nil {
fmt.Println(err)
}
path := "/dns/edit/" + domain + "/" + record.ID
resp := postRequest(path, jsonBody)
if resp.StatusCode == http.StatusOK {
log.Printf("Record updated for %v", record)
} else {
log.Printf("Unable to update record for %v, status %v", record, resp.StatusCode)
}
}
func filterRecords(ip string, records []Record) []Record {
var fr []Record
for _, v := range records {
if strings.Contains(v.Name, domain) && v.RecordType == "A" && v.Content != ip {
v.Content = ip
if v.Name == domain {
v.Name = ""
} else {
v.Name = strings.Split(v.Name, ".")[0]
}
fr = append(fr, v)
}
}
return fr
}
func loadSecrets() {
bytes := readJSONFile("secrets.json")
json.Unmarshal(bytes, &secrets)
}
func readJSONFile(filename string) []byte {
jsonFile, err := os.Open(filename)
if err != nil {
fmt.Println(err)
}
defer jsonFile.Close()
bytes, err := ioutil.ReadAll(jsonFile)
if err != nil {
fmt.Println(err)
}
return bytes
}
func readJSONFileToStruct(filename string, s *interface{}) {
jsonFile, err := os.Open(filename)
if err != nil {
fmt.Println(err)
}
defer jsonFile.Close()
bytes, err := ioutil.ReadAll(jsonFile)
if err != nil {
fmt.Println(err)
}
json.Unmarshal(bytes, &s)
}
func updateIP(ip string) {
prevIP, _ := getPrevIP()
if prevIP != ip {
setPrevIP(ip)
}
}
func getPrevIP() (string, error) {
file, err := os.Open(filepath)
if err != nil {
return "", err
}
defer file.Close()
var ip string
decoder := gob.NewDecoder(file)
decoder.Decode(&ip)
return ip, nil
}
func setPrevIP(ip string) {
f, err := os.Create(filepath)
if err != nil {
log.Fatalln("Error opening/creating file: ", err)
}
encoder := gob.NewEncoder(f)
err = encoder.Encode(ip)
if err != nil {
log.Fatalln("Error encoding gob: ", err)
}
f.Close()
}
func postRequest(path string, body []byte) *http.Response {
client := &http.Client{}
req, err := http.NewRequest("POST", BASE_PATH+path, bytes.NewReader(body))
resp, err := client.Do(req)
if err != nil {
fmt.Println(err)
}
return resp
}