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_role" "cross_account_developer" {
  name = "cross_account_developer"
}

resource "aws_iam_role_policy_attachment" "cross_account_developer_event_bus" {
  policy_arn = aws_iam_policy.atlas_um_event_bus_publisher.arn
  role       = data.aws_iam_role.cross_account_developer.name
}

data "aws_iam_policy_document" "eventbridge_log_publishing_policy" {
  statement {
    sid = "TrustEventsToStoreLogEvent"
    actions = [
      "logs:CreateLogStream",
      "logs:PutLogEvents",
      "logs:PutLogEventsBatch",
    ]

    resources = ["arn:aws:logs:${var.aws_region_id}:${local.account_id}:log-group:/aws/events/*:*"]

    principals {
      identifiers = ["events.amazonaws.com", "delivery.logs.amazonaws.com"]
      type        = "Service"
    }
  }
}

resource "aws_cloudwatch_log_resource_policy" "eventbridge_log_publishing_policy" {
  policy_document = data.aws_iam_policy_document.eventbridge_log_publishing_policy.json
  policy_name     = "TrustEventsToStoreLogEvents"
}

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
}

data "aws_iam_role" "deployment_role" {
  name = "cross_account_deployment_role"
}

data "aws_iam_policy_document" "ecs_agent_policy_document" {
  version   = "2012-10-17"
  policy_id = "${local.name_prefix}-ecs-agent"

  statement {
    sid    = "AllowECS"
    effect = "Allow"

    actions = [
      "ecs:CreateService",
      "ecs:CreateTaskSet",
      "ecs:DescribeClusters",
      "ecs:DescribeContainerInstances",
      "ecs:DescribeServices",
      "ecs:DescribeTaskDefinition",
      "ecs:DescribeTaskSets",
      "ecs:DescribeTasks",
      "ecs:DiscoverPollEndpoint",
      "ecs:ListClusters",
      "ecs:ListContainerInstances",
      "ecs:ListServices",
      "ecs:ListTagsForResource",
      "ecs:ListTaskDefinitionFamilies",
      "ecs:ListTaskDefinitions",
      "ecs:ListTasks",
      "ecs:Poll",
      "ecs:RegisterContainerInstance",
      "ecs:RegisterTaskDefinition",
      "ecs:RunTask",
      "ecs:StartTask",
      "ecs:SubmitContainerStateChange",
      "ecs:SubmitTaskStateChange",
      "ecs:TagResource",
      "ecs:UntagResource",
      "ecs:UpdateContainerAgent",
      "ecs:UpdateContainerInstancesState",
      "ecs:UpdateService",
      "ecs:UpdateServicePrimaryTaskSet",
      "ecs:UpdateTaskSet",
    ]

    resources = ["*"]
  }

  statement {
    sid    = "AllowECR"
    effect = "Allow"

    actions = [
      "ecr:BatchCheckLayerAvailability",
      "ecr:BatchGetImage",
      "ecr:CompleteLayerUpload",
      "ecr:CreateRepository",
      "ecr:DescribeImages",
      "ecr:DescribeRepositories",
      "ecr:GetAuthorizationToken",
      "ecr:GetDownloadUrlForLayer",
      "ecr:GetRepositoryPolicy",
      "ecr:InitiateLayerUpload",
      "ecr:ListImages",
      "ecr:ListTagsForResource",
      "ecr:PutImage",
      "ecr:TagResource",
      "ecr:UntagResource",
      "ecr:UploadLayerPart",
    ]

    resources = ["*"]
  }

  statement {
    sid    = "AllowGetPassRole"
    effect = "Allow"

    actions = [
      "iam:GetRole",
      "iam:PassRole",
    ]

    resources = [
      "arn:aws:iam::*:role/*"
    ]
  }
}

resource "aws_iam_policy" "ecs_agent_policy" {
  name   = "${local.name_prefix}-ecs-agent"
  policy = data.aws_iam_policy_document.ecs_agent_policy_document.json
}

resource "aws_iam_role_policy_attachment" "deployment_role_ecs_ecr" {
  role       = data.aws_iam_role.deployment_role.id
  policy_arn = aws_iam_policy.ecs_agent_policy.arn
}

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

  name        = "s3_deployment"
  name_prefix = local.name_prefix
  bucket_masks = [
    module.static_files.bucket.id,

  ]
}

resource "aws_iam_role_policy_attachment" "deployment_role_s3" {
  policy_arn = module.s3_bucket_rw.policy.arn
  role       = data.aws_iam_role.deployment_role.id
}

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
  ]
}
