//go:build ignore
// +build ignore

// This program generates data.go from Mozilla Included CA Certificate List.
// https://wiki.mozilla.org/CA/Included_Certificates
package main

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"net/http"
	"os"
)

// Link from: https://wiki.mozilla.org/CA/Included_Certificates
// PEM of Root Certificates in Mozilla's Root Store with the Websites (TLS/SSL) Trust Bit Enabled
const mozillaRootStoreWebsiteTrustBitEnabledURL = "https://ccadb.my.salesforce-sites.com/mozilla/IncludedRootsPEMTxt?TrustBitsInclude=Websites"

const header = `// Code generated by generate_data. DO NOT EDIT.

// This file contains embedded root certificates from "Mozilla Included
// CA Certificate List" (https://wiki.mozilla.org/CA/Included_Certificates).
//
// Use of these certificates is governed by Mozilla Public License 2.0
// that can be found in the LICENSE.certificates file.

package embedded

const data = `

func main() {
	resp, err := http.Get(mozillaRootStoreWebsiteTrustBitEnabledURL)
	if err != nil {
		fail("error getting root certificates from mozilla: %v", err)
	}
	defer resp.Body.Close()

	data, err := io.ReadAll(resp.Body)
	if err != nil {
		fail("error reading http body: %v", err)
	}

	data = bytes.ReplaceAll(data, []byte("\r"), []byte{})

	of, err := os.Create("embedded/data.go")
	if err != nil {
		fail("error creating data.go: %v", err)
	}

	buf := bufio.NewWriter(of)
	buf.WriteString(header)

	buf.WriteString("`")
	buf.WriteString(string(data))
	buf.WriteString("`\n")

	err = buf.Flush()
	if err != nil {
		fail("error writing to data.go: %v", err)
	}

	err = of.Close()
	if err != nil {
		fail("error closing data.go: %v", err)
	}
}

func fail(format string, args ...interface{}) {
	fmt.Fprintf(os.Stderr, format+"\n", args...)
	os.Exit(1)
}
