module "logging_policy" {
  source      = "../../../modules/iam/policies/logging"
  name_prefix = local.name_prefix
}

resource "aws_iam_role" "ecs_tasks_runner" {
  name = "${local.name_prefix}-ecs-task_execution_role"

  assume_role_policy = <<POLICY
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": "ecs-tasks.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
POLICY
  tags               = local.common_tags
}

resource "aws_iam_role_policy_attachment" "ssm" {
  role       = aws_iam_role.ecs_tasks_runner.id
  policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
}

resource "aws_iam_role_policy_attachment" "secrets" {
  role       = aws_iam_role.ecs_tasks_runner.id
  policy_arn = module.kms_secrets_manager.secrets_deployment_ro_policy.arn
}

resource "aws_iam_role_policy_attachment" "logging" {
  role       = aws_iam_role.ecs_tasks_runner.id
  policy_arn = module.logging_policy.policy.arn
}

data "aws_iam_policy_document" "atlas_um_event_bus_publisher" {
  version = "2012-10-17"
  statement {
    actions = [
      "events:DescribeEventBus",
      "events:ListEventBuses",
      "events:PutEvents",
    ]
    effect = "Allow"
    resources = [
      aws_cloudwatch_event_bus.atlas_um_event_bus.arn
    ]
  }
}

resource "aws_iam_policy" "atlas_um_event_bus_publisher" {
  name        = "${local.name_prefix}-atlas_um_event_bus_publisher"
  description = "Allow publish to Atlas UM event bus."
  policy      = data.aws_iam_policy_document.atlas_um_event_bus_publisher.json
}

resource "aws_iam_role" "event_bus_invoke_remote_event_bus" {
  name               = "${local.name_prefix}-event_bus_invoke_remote_event_bus"
  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": "events.amazonaws.com"
      },
      "Effect": "Allow"
    }
  ]
}
EOF
}

module "s3_static_notifications_rw_policy" {
  source = "../../../modules/iam/policies/s3/buckets_rw"

  name        = "s3_static_notifications_rw_policy"
  name_prefix = local.name_prefix

  bucket_masks = [
    module.static_notifications.bucket.bucket
  ]
}
