package clusters

import (
	"fmt"

	"code.justin.tv/d8a/buddy/lib/config"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/rds"
	"github.com/aws/aws-sdk-go/service/rds/rdsiface"
	"github.com/pkg/errors"
)

func SetSuperUserPassword(rdsClient rdsiface.RDSAPI, cluster *config.Cluster, password string) error {
	var err error

	if cluster.IsAurora {
		_, err = rdsClient.ModifyDBCluster(&rds.ModifyDBClusterInput{
			DBClusterIdentifier: aws.String(cluster.RootIdentifier),
			MasterUserPassword:  aws.String(password),
		})
	} else {
		_, err = rdsClient.ModifyDBInstance(&rds.ModifyDBInstanceInput{
			DBInstanceIdentifier: aws.String(cluster.RootIdentifier),
			MasterUserPassword:   aws.String(password),
		})
	}

	if err != nil {
		return errors.Wrap(err, fmt.Sprintf("could not change the superuser password of cluster %s", cluster.Name))
	}

	return nil
}
