package services

import (
	"regexp"
	"strings"
)

var keyAssign = regexp.MustCompile(`([A-Za-z_][A-Za-z0-9_]*)=`)

func DeriveOutputs(script string) []string {
	out := []string{}
	seen := map[string]bool{}
	for _, line := range strings.Split(script, "\n") {
		if !strings.Contains(line, "WORKFLOW_ENV") {
			continue
		}
		for _, m := range keyAssign.FindAllStringSubmatch(line, -1) {
			key := m[1]

			if key == "WORKFLOW_ENV" || key == "env" {
				continue
			}
			if seen[key] {
				continue
			}
			seen[key] = true
			out = append(out, key)
		}
	}
	return out
}

// Slugify lived here and was mirrored by hand in sitesvc. It now has a single
// definition in shared/provision, which both services import.
