package e2eutil

import (
	"fmt"
	"os"
	"os/exec"

	"code.justin.tv/eventbus/controlplane/internal/e2eaccounts"
)

func Converge() error {
	// pass credentials as environment variables into the script
	creds, err := e2eaccounts.AccountCredentials().MainAccount.Get()
	if err != nil {
		return err
	}
	accessKeyVar := fmt.Sprintf("AWS_ACCESS_KEY_ID=%s", creds.AccessKeyID)
	secretKeyVar := fmt.Sprintf("AWS_SECRET_ACCESS_KEY=%s", creds.SecretAccessKey)
	sessionTokenVar := fmt.Sprintf("AWS_SESSION_TOKEN=%s", creds.SessionToken)

	// Run converge with access credentials passed on the command line
	cmd := exec.Command("go", "run", "./cmd/converger/main.go", "-once")
	cmd.Env = append(os.Environ(), accessKeyVar, secretKeyVar, sessionTokenVar)

	err = cmd.Start()
	if err != nil {
		return err
	}

	return cmd.Wait()
}
