// +build ignore

package main

import (
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"text/template"
	"time"
)

func main() {
	const url = "https://mkcert.org/generate/"
	resp, err := http.Get(url)
	if err != nil {
		log.Fatal(err)
	}
	if resp.StatusCode != 200 {
		log.Fatal("expected 200, got", resp.StatusCode)
	}
	defer resp.Body.Close()

	bundle, err := ioutil.ReadAll(resp.Body)

	fp, err := os.Create("certifi.go")
	if err != nil {
		log.Fatal(err)
	}
	defer fp.Close()

	tmpl.Execute(fp, struct {
		Timestamp time.Time
		URL       string
		Bundle    string
	}{
		Timestamp: time.Now(),
		URL:       url,
		Bundle:    string(bundle),
	})
}

var tmpl = template.Must(template.New("").Parse(`// Code generated by go generate; DO NOT EDIT
// {{ .Timestamp }}
// {{ .URL }}

package gocertifi

//go:generate go run gen.go

import (
	"crypto/x509"
	"errors"
)

const pemcerts string = ` + "`" + `
{{ .Bundle }}
` + "`" + `

var ErrParseFailed = errors.New("gocertifi: error when parsing certificates")

// CACerts builds an X.509 certificate pool containing the Mozilla CA
// Certificate bundle. Returns nil on error along with an appropriate error
// code.
func CACerts() (*x509.CertPool, error) {
	pool := x509.NewCertPool()
	ok := pool.AppendCertsFromPEM([]byte(pemcerts))
	if !ok {
		return nil, ErrParseFailed
	}
	return pool, nil
}
`))
