package beanstalk

import (
	"encoding/json"
	"io/ioutil"
	"log"

	"code.justin.tv/foundation/xray/internal/plugins"
)

func init() {
	if plugins.InstancePluginMetadata != nil && plugins.InstancePluginMetadata.BeanstalkMetadata == nil {
		addPluginMetadata(plugins.InstancePluginMetadata)
	}
}

func addPluginMetadata(pluginmd *plugins.PluginMetadata) {
	//Assume users of this package are running on Elastic Beanstalk, which automatically creates an environment file at this location
	ebConfigPath := "/var/elasticbeanstalk/xray/environment.conf"

	rawConfig, err := ioutil.ReadFile(ebConfigPath)
	if err != nil {
		log.Printf("Unable to read EB config %v", err)
		return
	}

	config := &plugins.BeanstalkMetadata{}
	err = json.Unmarshal(rawConfig, config)
	if err != nil {
		log.Printf("Unable to unmarshal config %v", err)
		return
	}

	pluginmd.BeanstalkMetadata = config
}
