//go:generate go run -mod=vendor git.rootprojects.org/root/go-gitver

package main

import (
	"bytes"
	"fmt"
	"go/format"
	"os"
	"text/template"
	"time"

	"git.rootprojects.org/root/go-gitver/gitver"
)

var GitRev, GitVersion, GitTimestamp string
var exitCode int
var verFile = "xversion.go"

func main() {
	pkg := "main"

	args := os.Args[1:]
	for i := range args {
		arg := args[i]
		if "-f" == arg || "--fail" == arg {
			exitCode = 1
		} else if ("--outfile" == arg || "-o" == arg) && len(args) > i+1 {
			verFile = args[i+1]
			args[i+1] = ""
		} else if "--package" == arg && len(args) > i+1 {
			pkg = args[i+1]
			args[i+1] = ""
		} else if "-V" == arg || "version" == arg || "-version" == arg || "--version" == arg {
			fmt.Println(GitRev)
			fmt.Println(GitVersion)
			fmt.Println(GitTimestamp)
			os.Exit(0)
		}
	}
	if "" != os.Getenv("GITVER_FAIL") && "false" != os.Getenv("GITVER_FAIL") {
		exitCode = 1
	}

	v, err := gitver.ExecAndParse()
	if nil != err {
		fmt.Fprintf(os.Stderr, "Failed to get git version: %s\n", err)
		if exitCode > 0 {
			os.Exit(exitCode)
		}
		v = &gitver.Versions{
			Timestamp: time.Now(),
		}
	}

	// Create or overwrite the go file from template
	var buf bytes.Buffer
	if err := versionTpl.Execute(&buf, struct {
		Package   string
		Timestamp string
		Version   string
		GitRev    string
	}{
		Package:   pkg,
		Timestamp: v.Timestamp.Format(time.RFC3339),
		Version:   v.Version,
		GitRev:    v.Rev,
	}); nil != err {
		panic(err)
	}

	// Format
	src, err := format.Source(buf.Bytes())
	if nil != err {
		panic(err)
	}

	// Write to disk (in the Current Working Directory)
	f, err := os.Create(verFile)
	if nil != err {
		panic(err)
	}
	if _, err := f.Write(src); nil != err {
		panic(err)
	}
	if err := f.Close(); nil != err {
		panic(err)
	}

}

var versionTpl = template.Must(template.New("").Parse(`// Code generated by go generate; DO NOT EDIT.
package {{ .Package }}

func init() {
	{{ if .GitRev -}}
	GitRev = "{{ .GitRev }}"
	{{ end -}}
	{{ if .Version -}}
	GitVersion = "{{ .Version }}"
	{{ end -}}
	GitTimestamp = "{{ .Timestamp }}"
}
`))
