package awsutils

import (
	"fmt"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
	"github.com/aws/aws-sdk-go/aws/ec2metadata"
	"github.com/aws/aws-sdk-go/aws/session"
)

func GetSession(config *aws.Config, roleArn string) (*session.Session, error) {
	sess, err := session.NewSession(config.Copy())
	if err != nil {
		return nil, fmt.Errorf("session.NewSession: %s", err)
	}

	region, err := ec2metadata.New(sess).Region()
	if err == nil && region != "" {
		sess = sess.Copy(&aws.Config{Region: aws.String(region)})
	}

	if roleArn != "" {
		sess = sess.Copy(&aws.Config{Credentials: stscreds.NewCredentials(sess, roleArn)})
	}

	return sess, nil
}
