//go:build ignore
// +build ignore

// Code Generation using fiat-crypto
//
// Download and unpack Fiat Cryptography v0.1.4 from
// https://github.com/mit-plv/fiat-crypto/releases/tag/v0.1.4
//
// Then run this program specifying the path to the Fiat Cryptography v0.1.4 binary.
//  $ FIAT_BINARY=<path to binary> go run genFiatMont.go
//
// References:
// [1] Erbsen et al. "Simple High-Level Code For Cryptographic Arithmetic – With
// Proofs, Without Compromises" https://github.com/mit-plv/fiat-crypto

package main

import (
	"log"
	"os"
	"os/exec"
	"strings"
	"text/template"
)

const headerCIRCL = "Code generated by fiat.go using fiat-crypto v0.1.4."

var FIAT_PARAMS = []string{
	"word-by-word-montgomery",
	"--output", "{{.Pkg}}/fiatMont.go",
	"--lang", "Go",
	"--package-name", "{{.Pkg}}",
	"--doc-prepend-header", headerCIRCL,
	"--package-case", "lowerCamelCase",
	"--public-function-case", "lowerCamelCase",
	"--public-type-case", "lowerCamelCase",
	"--doc-newline-before-package-declaration",
	"--no-primitives",
	"--widen-carry",
	"--no-field-element-typedefs",
	"--relax-primitive-carry-to-bitwidth", "64",
	"Fp", "64", "{{.Prime}}", "add", "sub", "mul", "square",
}

var fields = []struct{ Pkg, Prime string }{
	{
		Pkg:   "fp64",
		Prime: "0xffffffff00000001", // 2^32 * 4294967295 + 1
	},
	{
		Pkg:   "fp128",
		Prime: "0xffffffffffffffe40000000000000001", // 2^66 * 4611686018427387897 + 1
	},
}

func main() {
	FIAT_BINARY := os.Getenv("FIAT_BINARY")
	if FIAT_BINARY == "" {
		log.Fatal("error: must specify the path to the Fiat Cryptography binary.")
	}

	paramsTmpl := strings.Join(FIAT_PARAMS, ",")

	for _, f := range fields {
		var buf strings.Builder
		t := template.Must(new(template.Template).Parse(paramsTmpl))
		err := t.Execute(&buf, f)
		if err != nil {
			log.Fatalf("error: executing template: %v", err)
		}

		cmdParams := strings.Split(buf.String(), ",")
		cmd := exec.Command(FIAT_BINARY, cmdParams...)
		out, err := cmd.CombinedOutput()
		if len(out) != 0 || err != nil {
			log.Fatalf("command output: %s\n command error: %v\n", out, err)
		}
	}
}
