package terraform

import (
	"fmt"
	"os/exec"
	"strings"
)

// Version will return the version and commit of the installed terraform. If
// terraform is not installed it will return an error.
func Version() (string, string, error) {
	cmd := exec.Command("terraform", "version")
	out, err := cmd.Output()
	if err != nil {
		return "", "", err
	}

	version, commit, err := parseVersion(out)
	if err != nil {
		return "", "", fmt.Errorf("Unable to determine version of terraform: %v", err)
	}

	return version, commit, nil
}

// parseVersion is a testable function that will take the information out of
// `terraform version` and return the version and commit.
func parseVersion(output []byte) (string, string, error) {
	fields := strings.Fields(string(output))
	if len(fields) >= 3 {
		return fields[1], strings.Trim(fields[2], "()"), nil
	}
	if len(fields) == 2 {
		return fields[1], "official", nil
	}

	return "", "", fmt.Errorf("%q does not appear to be valid input", output)
}
