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" "reporting_task_role" {
    statement {
    sid = "reportingECSTaskExecution"
    effect = "Allow"
    actions = [
      "ecr:GetAuthorizationToken",
      "ecr:BatchCheckLayerAvailability",
      "ecr:GetDownloadUrlForLayer",
      "ecr:BatchGetImage",
      "logs:CreateLogStream",
      "logs:PutLogEvents"
    ]
    resources = ["*"]
  }
  statement {
    sid = "reportingSecretsAccess"
    effect = "Allow"
    actions = [
      "ssm:get*"
    ]
    resources = [
      "arn:aws:ssm:us-east-1:721086286010:parameter/*"
    ]
  }
}

resource "aws_iam_policy" "reporting_task_role" {
  name = "${local.service_name}${local.iam_suffix}"
  policy = data.aws_iam_policy_document.reporting_task_role.json
}

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

resource "aws_iam_role_policy_attachment" "reporting_task_role_policy_attach" {
  role = aws_iam_role.reporting_task_role.name
  policy_arn = aws_iam_policy.reporting_task_role.arn
}


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

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

#
##
### 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" "reporting_service" {
  name = "reporting_service"
  count = local.deploy_env_name == "sandbox" ? 1 : 0
}
# this credential lives in sandbox-credentials
resource "aws_iam_access_key" "reporting_service" {
  user = aws_iam_user.reporting_service[count.index].name
  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_reporting" {
  user       = aws_iam_user.reporting_service[count.index].name
  policy_arn = aws_iam_policy.internal_profile_policy_copy.arn
  count = local.deploy_env_name == "sandbox" ? 1 : 0
}

resource "aws_iam_user_policy_attachment" "task_role_reporting" {
  user       = aws_iam_user.reporting_service[count.index].name
  policy_arn = aws_iam_policy.reporting_task_role.arn
  count = local.deploy_env_name == "sandbox" ? 1 : 0
}
