// +build continuous_profiler_stackdriver

package monitoring

import (
	"net/url"
	"os"

	"cloud.google.com/go/profiler"
	"gitlab.com/gitlab-org/labkit/log"
)

const profilerEnvKey = "GITLAB_CONTINUOUS_PROFILING"

// Exposing to tests
var profStart = profiler.Start

func initProfiler(opts profilerOpts) {
	driverParams, exists := os.LookupEnv(profilerEnvKey)
	if !exists {
		return
	}

	u, err := url.Parse(driverParams)
	if err != nil {
		log.WithError(err).Warn("unable to parse env var content")
		return
	}

	query := u.Query()
	driverName := u.Path

	if driverName != "stackdriver" {
		log.WithField("driver", driverName).Warn("unkown driver")
		return
	}

	config := profiler.Config{
		Service:        query.Get("service"),
		ServiceVersion: query.Get("service_version"),
		ProjectID:      query.Get("project_id"),
	}

	// If the service version is given through opts, it takes precedence.
	if opts.ServiceVersion != "" {
		config.ServiceVersion = opts.ServiceVersion
	}

	if err := profStart(config); err != nil {
		log.WithError(err).Warnf("unable to initialize %v profiler", driverName)
		return
	}

	log.WithFields(log.Fields{
		"driver":         driverName,
		"service":        config.Service,
		"serviceVersion": config.ServiceVersion,
		"projectId":      config.ProjectID,
	}).Info("profiler enabled")
}
