provider "aws" {
  region = "us-east-1"
}

data "aws_caller_identity" "current" {}
data "aws_region" "current" {}

# Variables
variable "scaleops_external_id" {
  description = "The external ID provided by ScaleOps for secure role assumption. Use the value from the dashboard."
  type        = string
  validation {
    condition     = length(var.scaleops_external_id) == 36
    error_message = "The external_id must be exactly 36 characters."
  }
}

variable "role_name" {
  type        = string
  description = "Name of the new IAM role to be used by ScaleOps for Marketplace Integration access"
  default     = "scaleops-marketplace-integration-access-role"
}

variable "policy_name" {
  type        = string
  description = "Name of the new policy"
  default     = "scaleops-marketplace-integration-access-policy"
}

variable "tags" {
  description = "A map of tags to assign to all resources"
  type        = map(string)
  default     = {}
}

# IAM Role
resource "aws_iam_role" "scaleops_marketplace_integration_access_role" {
  name = var.role_name
  tags = var.tags

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect = "Allow"
      Principal = {
        AWS = "arn:aws:iam::427621738444:role/ScaleOps-AssumeRoleDelegator"
      }
      Action = [
        "sts:AssumeRole",
        "sts:TagSession"
      ]
      Condition = {
        StringEquals = {
          "sts:ExternalId" = var.scaleops_external_id
        }
      }
    }]
  })
}

resource "aws_iam_role_policy" "scaleops_marketplace_integration_access_policy" {
  name = var.policy_name
  role = aws_iam_role.scaleops_marketplace_integration_access_role.id

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Sid    = "SimulateIAM"
        Effect = "Allow"
        Action = [
          "iam:SimulatePrincipalPolicy"
        ]
        Resource = "*"
      },
      {
        Sid    = "MarketplaceTagging"
        Effect = "Allow"
        Action = [
          "ec2:CreateTags"
        ]
        Resource = "arn:aws:ec2:*:*:volume/*"
      }
    ]
  })
}

# Outputs
output "role_arn" {
  description = "ARN of the created IAM role"
  value       = aws_iam_role.scaleops_marketplace_integration_access_role.arn
}

output "role_name" {
  description = "Name of the created IAM role"
  value       = aws_iam_role.scaleops_marketplace_integration_access_role.name
}

# Usage examples:
#
# module "scaleops_marketplace_integration" {
#   source = "https://scriptshelf.scaleops.com/aws/marketplace/integrate.tf.tar.gz"
#
#   scaleops_external_id = "EXTERNAL_ID_FROM_SCALEOPS_DASHBOARD"
# }
