data "aws_iam_policy_document" "ecs_assume_role" {
  statement {
    sid     = "AllowAssumeRoleFromECSTasks"
    effect  = "Allow"
    actions = ["sts:AssumeRole"]

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

data "aws_iam_policy_document" "notification_task_role" {

  statement {
    sid = "NotificationSecretsSecretsAccess"
    effect = "Allow"
    actions = [
      "secretsmanager:GetSecretValue",
      "ses:*",
      "logs:PutLogEvents",
      "logs:CreateLogStream",
      "sqs:Get*",
      "sqs:Receive*",
      "sqs:Send*",
      "sqs:DeleteMessage"
    ]
    resources = ["*"]
  }

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

resource "aws_iam_policy" "notification_task_role" {
  name = "${var.service_name}${local.workspace["iam_suffix"]}"
  policy = data.aws_iam_policy_document.notification_task_role.json
}

resource "aws_iam_role" "notification_task_role" {
  name = "${var.service_name}-task-role${local.workspace["iam_suffix"]}"
  assume_role_policy = data.aws_iam_policy_document.ecs_assume_role.json
}

resource "aws_iam_role_policy_attachment" "notification_task_role_policy_attach" {
  role = aws_iam_role.notification_task_role.name
  policy_arn = aws_iam_policy.notification_task_role.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" "notification_service" {
  name = "notification_service"
  count = local.workspace["deploy_env_name"] == "sandbox" ? 1 : 0
}
# this credential lives in mop-utils/sandbox-credentials
resource "aws_iam_access_key" "notification_service" {
  user = aws_iam_user.notification_service[count.index].name
  count = local.workspace["deploy_env_name"] == "sandbox" ? 1 : 0
}

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

/* 
output notification_aws_access_key_id {
  value = aws_iam_access_key.notification_service.*.id
}
output notification_aws_secret_access_key {
  value = aws_iam_access_key.notification_service.*.secret
}
 */
