// Wrapper package to report errors to Rollbar

package report

import (
	"time"

	"code.justin.tv/common/golibs/bininfo"
	"code.justin.tv/foundation/history-worker/configuration"
	"code.justin.tv/systems/sandstorm/manager"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/sts"
	"github.com/stvp/rollbar"
)

const (
	sandstormRoleArn   = "arn:aws:iam::734326455073:role/sandstorm/production/templated/role/history-"
	sandstormTableName = "sandstorm-production"
	sandstormKeyId     = "alias/sandstorm-production"
)

func init() {
	rollbar.Token = RollbarToken()
	rollbar.Environment = configuration.Environment()
	rollbar.CodeVersion = bininfo.Revision()
}

/*
Fetches rollbar token from sandstorm. Need to have
AWS_ACCESS_KEY and AWS_SECRET_ACCESS_KEY set as env
vars to run
*/
func RollbarToken() string {
	token := configuration.Resolve("rollbarToken")

	if token != "" {
		return token
	}

	env := configuration.Environment()
	awsConfig := &aws.Config{Region: aws.String("us-west-2")}
	stsclient := sts.New(session.New(awsConfig))

	arp := &stscreds.AssumeRoleProvider{
		ExpiryWindow: 10 * time.Second,
		RoleARN:      sandstormRoleArn + env,
		Client:       stsclient,
	}

	credentials := credentials.NewCredentials(arp)
	awsConfig.WithCredentials(credentials)

	sandstormManager := manager.New(manager.Config{
		AWSConfig: awsConfig,
		TableName: sandstormTableName,
		KeyID:     sandstormKeyId,
	})

	secret, err := sandstormManager.Get("web-rails/history/" + env + "/rollbarToken")
	if err != nil {
		panic(err)
	}

	return string(secret.Plaintext)
}

// Reports a warning to rollbar
func RollbarWarn(err error) {
	rollbar.Error(rollbar.WARN, err)
}

// Main function which reports error to rollbar in a subroutine
func RollbarError(err error, fields ...*rollbar.Field) {
	var level string
	var trace rollbar.Stack

	switch e := err.(type) {
	case *CustomAlert:
		level = e.level
		trace = e.trace
	default:
		level = rollbar.ERR
		trace = rollbar.BuildStack(0)
	}

	rollbar.ErrorWithStack(level, err, trace, fields...)
}
