resource "aws_iam_role" "ec2_nexus" {
  name               = "${local.name_prefix}-nexus-ec2"
  description        = "Role for Jenkins EC2 slave instances"
  path               = "/"
  assume_role_policy = data.aws_iam_policy_document.ec2_server.json
}

resource "aws_iam_role_policy_attachment" "nexus_ssm" {
  role       = aws_iam_role.ec2_nexus.id
  policy_arn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
}

resource "aws_iam_instance_profile" "ec2_nexus" {
  name = "${local.name_prefix}-nexus-ec2"
  role = aws_iam_role.ec2_nexus.name
}

data "aws_iam_policy_document" "nexus_s3_policy" {
  statement {
    effect = "Allow"
    actions = [
      "s3:PutObject",
      "s3:GetObject",
      "s3:DeleteObject",
      "s3:ListBucket",
      "s3:GetLifecycleConfiguration",
      "s3:PutLifecycleConfiguration",
      "s3:PutObjectTagging",
      "s3:GetObjectTagging",
      "s3:DeleteObjectTagging",
      "s3:DeleteBucket",
      "s3:CreateBucket",
      "s3:GetBucketAcl"
    ]
    resources = [
      aws_s3_bucket.nexus_s3.arn,
      "${aws_s3_bucket.nexus_s3.arn}/*",
      "arn:aws:s3:::infra-nexus-artifacts/*",
      "arn:aws:s3:::infra-nexus-artifacts",
    ]
  }
}

resource "aws_iam_policy" "ec2_nexus_s3" {
  name        = "${local.name_prefix}-nexus-s3"
  path        = "/"
  description = "Allows Nexus use S3 bucket for blob storage"
  policy      = data.aws_iam_policy_document.nexus_s3_policy.json
}

resource "aws_iam_role_policy_attachment" "ec2_nexus_s3" {
  role       = aws_iam_role.ec2_nexus.id
  policy_arn = aws_iam_policy.ec2_nexus_s3.arn
}

resource "aws_iam_policy" "ec2_nexus_ecr" {
  name        = "${local.name_prefix}-nexus-ecr"
  path        = "/"
  description = "Allows Nexus to get images from infra ECR"
  policy      = <<POLICY
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "NexusECRRepoAccess",
            "Effect": "Allow",
            "Action": [
                "ecr:GetDownloadUrlForLayer",
                "ecr:BatchGetImage",
                "ecr:BatchCheckLayerAvailability"
            ],
            "Resource": "arn:aws:ecr:us-east-1:475275892927:repository/nexus3"
        },
        {
            "Sid": "NexusECRAuth",
            "Effect": "Allow",
            "Action": "ecr:GetAuthorizationToken",
            "Resource": "*"
        }
    ]
}
POLICY

}

resource "aws_iam_role_policy_attachment" "ec2_nexus_ecr" {
  role       = aws_iam_role.ec2_nexus.id
  policy_arn = aws_iam_policy.ec2_nexus_ecr.arn
}
