// Simple program to generate variables with the static code for the builder
// based on real .go source files.
// This allows for easier modification of the static code.
package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

const (
	delimiter = "// IMPORTANT: All code below this line is added to the parser as static code"

	header = `// This file is automatically generated by go generate
// Do not modify manually

package builder

var %s = ` + "`"

	footer = "`"

	eol = "\n"
)

func generateFile(source, dest, varname string) {
	staticCode, err := ioutil.ReadFile(source)
	if err != nil {
		panic(err)
	}

	lines := strings.Split(string(staticCode), eol)
	keep := false
	dstLines := make([]string, 0, len(lines))
	dstLines = append(dstLines, strings.Split(fmt.Sprintf(header, varname), eol)...)
	for _, line := range lines {
		if keep {
			dstLines = append(dstLines, line)
		}
		if line == delimiter {
			keep = true
		}
	}
	dstLines = append(dstLines, strings.Split(footer, eol)...)

	err = ioutil.WriteFile(dest, []byte(strings.Join(dstLines, eol)), 0644)
	if err != nil {
		panic(err)
	}
}

func main() {
	if len(os.Args) > 1 && os.Args[1] == "--" {
		os.Args = os.Args[2:]
	} else {
		os.Args = os.Args[1:]
	}
	if len(os.Args) < 3 {
		panic("not enough args")
	}
	generateFile(os.Args[0], os.Args[1], os.Args[2])
}
