Files
ddns-updater/internal/dns_providers/directadmin.go

92 lines
2.0 KiB
Go
Raw Normal View History

package dns_providers
import (
"context"
"fmt"
"log"
"time"
"github.com/levelzerotechnology/directadmin-go"
"hub.cybercinch.nz/cybercinch/ddns-update/internal"
)
const (
DirectadminTag = "directadmin"
)
type Directadmin struct {
Client *directadmin.UserContext
Context context.Context
Config internal.Config
}
type ListDNSRecordsParams struct {
Name string
}
func (d *Directadmin) FetchRecord(hostname string) (string, error) {
dnsRecord, err := d.GetDnsRecord(hostname)
if err != nil {
log.Fatal("unable to retrieve DNS record")
return "", err
}
return dnsRecord[0].Value, nil
}
func (d *Directadmin) UpdateRecord(hostname string, ip string) error {
result := GetDomainParts(hostname)
current_record, _ := d.GetDnsRecord(hostname)
// Create an updated record for the new ip
new_record := directadmin.DNSRecord{Name: current_record[0].Name, Ttl: current_record[0].Ttl, Type: current_record[0].Type, Value: ip}
err := d.Client.UpdateDNSRecord(result.Domain, current_record[0], new_record)
if err != nil {
return err
}
return nil
}
func (d *Directadmin) GetDnsRecord(hostname string) ([]directadmin.DNSRecord, error) {
domainParts := GetDomainParts(hostname)
dnsRecords, err := d.Client.GetDNSRecords(domainParts.Domain)
var slice []directadmin.DNSRecord
for _, dnsRecord := range dnsRecords {
if domainParts.Name == dnsRecord.Name {
slice = append(slice, dnsRecord)
}
}
if len(slice) == 0 {
return nil, fmt.Errorf("unable to find DNS record for %s", hostname)
}
return slice, err
}
func (d *Directadmin) NewClient(server_url string, username string, key string) {
api, err := directadmin.New(server_url, 5*time.Second, false, false)
if err != nil {
panic(err)
}
userCtx, err := api.LoginAsUser(username, key)
if err != nil {
panic(err)
}
d.Client = userCtx
}
func NewDirectAdminProvider(ctx context.Context, config internal.Config) *Directadmin {
c := &Directadmin{}
c.Context = ctx
c.Config = config
c.NewClient(config.DirectadminUrl, config.DirectadminUsername, config.DirectadminKey)
return c
}