103 lines
2.7 KiB
Go
103 lines
2.7 KiB
Go
package helpers
|
|
|
|
import (
|
|
"fmt"
|
|
"slices"
|
|
"strings"
|
|
|
|
"github.com/chmike/domain"
|
|
dm "github.com/maximotejeda/ddns/internal/application/core/domain"
|
|
"github.com/maximotejeda/ddns/internal/application/core/domain/cf"
|
|
)
|
|
|
|
type result struct {
|
|
cf.Result
|
|
}
|
|
|
|
// RootIdentify
|
|
// identify root domain from a list of dns records
|
|
// basically root will be example.com
|
|
// if splitted and > 2 then is a sub domain
|
|
// else if == 2 is root domain
|
|
func RootIdentify(domains []cf.Result) (roots map[string]dm.DomainRecords, err error) {
|
|
roots = map[string]dm.DomainRecords{}
|
|
for _, reg := range domains {
|
|
name := reg.Name
|
|
nameParts := strings.Split(name, ".")
|
|
|
|
// if the name is equal to the root actual name continue
|
|
if len(nameParts) > 2 {
|
|
r := strings.Join(nameParts[len(nameParts)-2:], ".")
|
|
if _, ok := roots[r]; !ok {
|
|
roots[r] = dm.DomainRecords{Domain: r}
|
|
}
|
|
if record, ok := roots[r]; ok {
|
|
record.Existing = append(record.Existing, dm.Record{ID: reg.ID, Name: name, Type: reg.Type, Content: reg.Content})
|
|
roots[r] = record
|
|
}
|
|
|
|
} else if len(nameParts) == 2 {
|
|
if _, ok := roots[reg.Name]; !ok {
|
|
roots[reg.Name] = dm.DomainRecords{Domain: reg.Name}
|
|
}
|
|
if record, ok := roots[reg.Name]; ok {
|
|
record.Domain = reg.Name
|
|
record.Existing = append(record.Existing, dm.Record{ID: reg.ID, Name: name, Type: reg.Type, Content: reg.Content})
|
|
roots[reg.Name] = record
|
|
} else {
|
|
fmt.Println(roots[reg.Name])
|
|
}
|
|
} else {
|
|
continue
|
|
}
|
|
|
|
}
|
|
return roots, err
|
|
}
|
|
|
|
// SubDomainIdentify
|
|
// Identify subdomains from a list of subdomains
|
|
func SubdomainIdentify(name string, domains []cf.Result) (res map[string]dm.DomainRecords, err error) {
|
|
res, _ = RootIdentify(domains)
|
|
// check if name contains domain
|
|
// check if root domain list is in name
|
|
for k, r := range res {
|
|
if strings.Contains(name, r.Domain) { // if domain is on subname
|
|
if !slices.ContainsFunc(r.Existing, func(x dm.Record) bool {
|
|
|
|
return x.Name == name
|
|
}) {
|
|
r.ToCreate = append(r.ToCreate, dm.Record{Name: name})
|
|
res[k] = r
|
|
} else {
|
|
fmt.Println(slices.ContainsFunc(r.Existing, func(x dm.Record) bool {
|
|
return x.Name == name
|
|
}))
|
|
}
|
|
} else {
|
|
r.ToCreate = append(r.ToCreate, dm.Record{Name: fmt.Sprintf("%s.%s", name, r.Domain)})
|
|
res[k] = r
|
|
}
|
|
}
|
|
return res, nil
|
|
}
|
|
|
|
// SelectedDomain
|
|
// return an string
|
|
func SelectDomain(name string, domains map[string]dm.DomainRecords) string {
|
|
for k, r := range domains {
|
|
if name == "*" {
|
|
return name
|
|
}
|
|
if strings.Contains(name, k) { // if domain is on subname
|
|
return name
|
|
} else {
|
|
if err := domain.Check(name); err != nil {
|
|
panic(err)
|
|
}
|
|
return fmt.Sprintf("%s.%s", name, r.Domain)
|
|
}
|
|
}
|
|
return ""
|
|
}
|