data "aws_iam_policy_document" "ecs_task_assume_role" {
  statement {
    sid     = "AllowAssumeRoleFromEcsTasks"
    effect  = "Allow"
    actions = ["sts:AssumeRole"]

    principals {
      type        = "Service"
      identifiers = ["ecs-tasks.amazonaws.com"]
    }
  }
}

data "aws_iam_policy_document" "gatewayv2_task_policy_doc" {
  statement {
    sid = "Gatewayv2ServiceSnsPublishAny"
    effect = "Allow"
    actions = ["sns:Publish"]
    resources = ["*"]
  }

  statement {
    sid = "Gatewayv2ECSTaskExecution"
    effect = "Allow"
    actions = [
      "ecr:GetAuthorizationToken",
      "ecr:BatchCheckLayerAvailability",
      "ecr:GetDownloadUrlForLayer",
      "ecr:BatchGetImage",
      "logs:CreateLogStream",
      "logs:PutLogEvents"
    ]
    resources = ["*"]
  }
}


resource "aws_iam_role" "gatewayv2_task_role" {
  name = "${local.service_name}-task-role${local.iam_suffix}"
  assume_role_policy = data.aws_iam_policy_document.ecs_task_assume_role.json
}


resource "aws_iam_role_policy_attachment" "profile_internal_policy_attach" {
  role = aws_iam_role.gatewayv2_task_role.name
  policy_arn = aws_iam_policy.internal_profile_policy_copy.arn
}

resource "aws_iam_policy" "internal_profile_policy_copy" {
  name = "gatewayv2-profile-internal${local.iam_suffix}"
  policy = data.terraform_remote_state.mop_core.outputs.tf_profile_internal_policy_document
}

resource "aws_iam_policy" "gatewayv2_task_policy_ecr" {
  name = "gatewayv2_task_policy${local.iam_suffix}"
  policy = data.aws_iam_policy_document.gatewayv2_task_policy_doc.json
}

resource "aws_iam_role_policy_attachment" "gatewayv2_task_policy_ecr_attach" {
  role = aws_iam_role.gatewayv2_task_role.name
  policy_arn = aws_iam_policy.gatewayv2_task_policy_ecr.arn
}

#
##
### if Sandbox then create a user with the same policies for localhost MOP
##
#

# create an IAM user for the localhost service
resource "aws_iam_user" "gatewayv2_service" {
  name = "gatewayv2_service${local.iam_suffix}"
  count = local.deploy_env_name == "sandbox" ? 1 : 0
}
# this credential lives in sandbox-credentials
resource "aws_iam_access_key" "gatewayv2_service" {
  user = "${aws_iam_user.gatewayv2_service[count.index].name}${local.iam_suffix}"
  count = local.deploy_env_name == "sandbox" ? 1 : 0
}

# attach the same policies held by the task role
resource "aws_iam_user_policy_attachment" "profile_internal_gatewayv2" {
  user       = aws_iam_user.gatewayv2_service[count.index].name
  policy_arn = aws_iam_policy.internal_profile_policy_copy.arn
  count = local.deploy_env_name == "sandbox" ? 1 : 0
}
