//go:build ignore

// rr_generate generates zpack.go which houses 2 large unpack/pack functions.

package main

import (
	"bytes"
	"flag"
	"html/template"
	"log"

	"codeberg.org/miekg/dns/internal/generate"
)

var hdr = `
// Code generated by "go run parse_generate.go"; DO NOT EDIT.

package dns

import "fmt"
import "codeberg.org/miekg/dns/internal/dnslex"

`

var parseFunc = template.Must(template.New("parseFunc").Parse(`
func parse(rr RR, c *dnslex.Lexer, o string) error {
	switch x := rr.(type) {
{{range .}}  case *{{.}}:
	return x.parse(c, o)
{{end}} }
	// if here, we don't have the RR in our pkg, check if it does Parser.
	if x, ok := rr.(Parser); ok {
		err := x.Parse(dnslex.Tokens(c), o)
		if err != nil {
			return &ParseError{err: err.Error()}
		}
		return nil
	}
	return &ParseError{err: fmt.Sprintf("no parse defined: %T", rr)}
}

`))

const out = "zparse.go"

func main() {
	flag.Parse()
	types, err := generate.Types("types.go")
	if err != nil {
		log.Fatalf("Failed to generate %s: %v", out, err)
	}

	etypes, err := generate.Types("edns_types.go")
	if err != nil {
		log.Fatalf("Failed to generate %s: %v", out, err)
	}
	etypes = []string{"ZONEVERSION", "EDE", "NSID"} // overwrite with the ones we have done

	types = append(types, etypes...)

	source := &bytes.Buffer{}
	source.WriteString(hdr)

	if err := parseFunc.Execute(source, types); err != nil {
		log.Fatalf("Failed to generate %s: %v", out, err)
	}

	generate.Write(source, out)
}
