package secretconf

import (
	"log"
	"time"

	"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/endpoints"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/sts"
)

// NewManager creates a new sandstorm manager instance. The region is
// defaulted to endpoints.UsWest2RegionID ("us-west-2")
func NewManager(roleARN string) *manager.Manager {
	return NewManagerWithRegion(roleARN, endpoints.UsWest2RegionID)
}

// NewManagerWithRegion is like NewManager, but allows specifying the AWS region
func NewManagerWithRegion(roleARN string, region string) *manager.Manager {
	sess, err := session.NewSession(&aws.Config{
		Region:              aws.String(region),
		STSRegionalEndpoint: endpoints.RegionalSTSEndpoint,
	})
	if err != nil {
		log.Fatal(err)
	}

	stsclient := sts.New(sess)

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

	creds := credentials.NewCredentials(arp)

	return manager.New(manager.Config{
		TableName: "sandstorm-production",
		KeyID:     "alias/sandstorm-production",
		AWSConfig: &aws.Config{
			Region:              aws.String(region),
			Credentials:         creds,
			STSRegionalEndpoint: endpoints.RegionalSTSEndpoint,
		},
	})
}
