package terraform

import (
	"io/ioutil"
	"regexp"
	"strings"
)

var elbRegexp *regexp.Regexp

func init() {
	elbRegexp = regexp.MustCompile(`elb_dns = ([-a-z0-9\.]*)`)
}

type hclVariable struct {
	Default     interface{}
	Description string
	Fields      []string `hcl:",decodedFields"`
}

type container struct {
	Variable map[string]*hclVariable
}

func IncrementASGCounts(path string) error {
	body, err := loadVariableFile(path)
	if err != nil {
		return err
	}

	body, err = incrementCounts(body)
	if err != nil {
		return err
	}

	err = ioutil.WriteFile(path, []byte(body), 0644)
	if err != nil {
		return err
	}

	return nil
}

func loadVariableFile(path string) (string, error) {
	body, err := ioutil.ReadFile(path)
	if err != nil {
		return "", err
	}

	return string(body), nil
}

func incrementCounts(body string) (string, error) {
	body = strings.Replace(body, "max_size = 0", "max_size = 1", 1)
	body = strings.Replace(body, "min_size = 0", "min_size = 1", 1)
	body = strings.Replace(body, "canary_size = 0", "canary_size = 1", 1)

	return body, nil
}
