// +build continuous_profiler_stackdriver

package monitoring

import (
	"net/url"
	"os"

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

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("unknown driver")
		return
	}

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

		MutexProfiling: true,
	}

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

	var clientOpts []option.ClientOption
	if opts.CredentialsFile != "" {
		clientOpts = append(clientOpts, option.WithCredentialsFile(opts.CredentialsFile))
	}

	if err := profStart(config, clientOpts...); 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")
}
