package main

import (
	"bytes"
	"log"
	"os"

	"text/template"
)

func buildBindResponsePolicyFile() {
	var (
		output bytes.Buffer
	)

	outputTemplate := `{{- $domain := .Domain -}}
$TTL {{ or .TTL "1h" }}
@	IN	SOA	{{ $domain }}.	{{ or .Email "domain-admin" }}.	(
			{{ or .Serial "0000000000" }}	; Serial
			{{ or .Refresh "1h" }}			; Refresh
			{{ or .Retry "30m" }}			; Retry
			{{ or .Expire "1w" }}			; Expire
			{{ or .Minimum "1h" }}			; Minimum
)

;
;	Name Servers
;
{{- range .NameServers }}
			IN	NS	{{ . }}.
{{- end }}

;
;	Addresses
;
{{- range .BlockedDomains }}
{{ . }}		IN	CNAME	blocked.{{ $domain }}.
{{- end }}
`

	t, err := template.New("response-policy-zone").Parse(outputTemplate)
	if err != nil {
		log.Fatalf("[FATAL] Unable to parse template (%s): %v\n", "response-policy-zone", err)
	}

	if err := t.Execute(&output, config.Config.ZoneConfig); err != nil {
		log.Fatalf("[FATAL] Unable to generate template output: %v\n", err)
	}

	fileWriter, err := os.Create(config.BindOutputFileName)
	if err != nil {
		log.Fatalf("[FATAL] Unable to open file (%s) for writing: %v", config.BindOutputFileName, err)
	}
	defer fileWriter.Close()

	bytesWritten, err := fileWriter.Write(output.Bytes())
	if err != nil {
		log.Fatalf("[FATAL] Unable to write to file (%s): %v", config.BindOutputFileName, err)
	}

	log.Printf("[DEBUG] Wrote %d bytes to %s.\n", bytesWritten, config.BindOutputFileName)
}
