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" "conflict_detection_task_role_doc" {

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

data "aws_iam_policy" "profile_internal_policy" {
  name = "profile-internal-policy-tf"
}

resource "aws_iam_policy" "conflict_detection_task_policy" {
  name = "${local.workspace["service_name"]}_policy"
  policy = data.aws_iam_policy_document.conflict_detection_task_role_doc.json
}

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

resource "aws_iam_role_policy_attachment" "conflict_detection_task_role_policy_attach" {
  role = aws_iam_role.conflict_detection_task_role.name
  policy_arn = aws_iam_policy.conflict_detection_task_policy.arn
}


resource "aws_iam_role_policy_attachment" "profile_internal_policy_attach" {
  role = aws_iam_role.conflict_detection_task_role.name
  policy_arn = data.aws_iam_policy.profile_internal_policy.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" "conflict_detection" {
  name = "conflict_detection"
  count = local.workspace["deploy_env_name"] == "sandbox" ? 1 : 0
}
# this credential lives in sandbox-credentials
resource "aws_iam_access_key" "conflict_detection" {
  user = aws_iam_user.conflict_detection[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" "profile_internal_conflict_detection" {
  user       = aws_iam_user.conflict_detection[count.index].name
  policy_arn = data.aws_iam_policy.profile_internal_policy.arn
  count = local.workspace["deploy_env_name"] == "sandbox" ? 1 : 0
}
resource "aws_iam_user_policy_attachment" "task_role_conflict_detection" {
  user       = aws_iam_user.conflict_detection[count.index].name
  policy_arn = aws_iam_policy.conflict_detection_task_policy.arn
  count = local.workspace["deploy_env_name"] == "sandbox" ? 1 : 0
}