// Package buildinfo resolves the product version embedded in a Notarius build.
package buildinfo

import (
	"fmt"
	"regexp"
	"runtime/debug"
)

var stableVersion = regexp.MustCompile(`^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$`)

// Override is set at link time for controlled builds.
var Override string

// Version returns the release version embedded in the build, or development
// when the build does not carry a stable release tag.
func Version() (string, error) {
	buildVersion := ""
	if info, ok := debug.ReadBuildInfo(); ok {
		buildVersion = info.Main.Version
	}
	return resolve(Override, buildVersion)
}

func resolve(override, buildVersion string) (string, error) {
	if override != "" {
		if !stableVersion.MatchString(override) {
			return "", fmt.Errorf("build version override is not a stable release tag")
		}
		return override, nil
	}
	if stableVersion.MatchString(buildVersion) {
		return buildVersion, nil
	}
	return "development", nil
}
