109 lines
2 KiB
Go
109 lines
2 KiB
Go
package main
|
|
|
|
import (
|
|
// Standard
|
|
"fmt"
|
|
"slices"
|
|
"strings"
|
|
)
|
|
|
|
type DNSRecord struct {
|
|
ID string `json:".id"`
|
|
Address string
|
|
Disabled string
|
|
Dynamic string
|
|
Name string
|
|
TTL string
|
|
Type string
|
|
}
|
|
|
|
type RecordsTree struct {
|
|
Record DNSRecord
|
|
Children []RecordsTree
|
|
}
|
|
|
|
func SortDNSRecord(a, b DNSRecord) int {
|
|
aComponents := strings.Split(a.Name, ".")
|
|
bComponents := strings.Split(b.Name, ".")
|
|
|
|
slices.Reverse(aComponents)
|
|
slices.Reverse(bComponents)
|
|
|
|
for i, aComp := range aComponents {
|
|
if i >= len(bComponents) {
|
|
return -1
|
|
}
|
|
|
|
bComp := bComponents[i]
|
|
if aComp > bComp {
|
|
return 1
|
|
}
|
|
|
|
if aComp < bComp {
|
|
return -1
|
|
}
|
|
|
|
}
|
|
|
|
return 0
|
|
}
|
|
|
|
func (r DNSRecord) Parts() int {
|
|
return len(strings.Split(r.Name, "."))
|
|
}
|
|
|
|
func (r DNSRecord) Part(numParts int) string {
|
|
splitName := strings.Split(r.Name, ".")
|
|
slices.Reverse(splitName)
|
|
|
|
parts := []string{}
|
|
for i := range numParts {
|
|
if i >= len(splitName) {
|
|
break
|
|
}
|
|
parts = append(parts, splitName[i])
|
|
}
|
|
|
|
slices.Reverse(parts)
|
|
return strings.Join(parts, ".")
|
|
}
|
|
|
|
func (r DNSRecord) NameReversed() string {
|
|
parts := strings.Split(r.Name, ".")
|
|
slices.Reverse(parts)
|
|
return strings.Join(parts, ".")
|
|
}
|
|
|
|
func (rt *RecordsTree) BuildTree(records []DNSRecord, startAt, partsLevel int) (tree RecordsTree) {
|
|
tree = RecordsTree{}
|
|
|
|
for i := startAt; i < len(records); i++ {
|
|
// current: bar.foo.n44.se
|
|
current := records[i]
|
|
currentPart := current.Part(partsLevel)
|
|
|
|
for j := i; j < len(records); j++ {
|
|
// next: baz.bar.foo.n44.se
|
|
next := records[j]
|
|
nextPart := next.Part(partsLevel)
|
|
fmt.Printf("%04d %04d: %s ?= %s\n", i, j, currentPart, nextPart)
|
|
|
|
if currentPart == nextPart {
|
|
fmt.Printf("FOUND SOMETHING!\n")
|
|
nextTree := RecordsTree{
|
|
Record: next,
|
|
}
|
|
|
|
tree.Children = append(tree.Children, nextTree)
|
|
}
|
|
|
|
// Doesn't match anymore, return to other loop after all that are processed
|
|
if currentPart != nextPart {
|
|
i = j
|
|
break
|
|
}
|
|
}
|
|
}
|
|
|
|
return tree
|
|
}
|