locals {
  registries = [
    "portal_server",
    "django_nginx", 
  ]
}

data "aws_vpc_endpoint_service" "ecr_api_endpoint" {
  service = "ecr.api"
}

data "aws_vpc_endpoint_service" "ecr_dkr_endpoint" {
  service = "ecr.dkr"
}

resource "aws_iam_instance_profile" "portal_server_instance_profile" {
  name     = "portal_server-instance-profile"
  role     = aws_iam_role.portal_server.name
}

resource "aws_iam_role" "portal_server" {
  name     = "portal-instance-role"

  assume_role_policy = <<EOF
{   
    "Version": "2012-10-17",
    "Statement": [
      {   
        "Sid": "", 
        "Effect": "Allow",
        "Principal": {
          "Service": [
            "ec2.amazonaws.com",
            "ssm.amazonaws.com"
            ]
        },
        "Action": "sts:AssumeRole"
      }
    ]
  }
EOF
}

data "aws_iam_policy_document" "portal_server_ecr_policy" {
  statement {
    actions = [
      "ecr:GetAuthorizationToken",
    ]

    resources = ["*"]
  }

  statement {
    sid    = "AllowCommunicationECR"
    effect = "Allow"

    actions = [
			"ecr:BatchCheckLayerAvailability",
			"ecr:GetDownloadUrlForLayer",
			"ecr:GetRepositoryPolicy",
			"ecr:DescribeRepositories",
			"ecr:ListImages",
			"ecr:DescribeImages",
			"ecr:BatchGetImage",
			"ecr:InitiateLayerUpload",
			"ecr:UploadLayerPart",
			"ecr:CompleteLayerUpload",
			"ecr:PutImage"
    ]

    resources = [
      "arn:${var.aws_partition}:ecr:${var.aws_region}:${var.common_services_account}:repository/portal_server",
      "arn:${var.aws_partition}:ecr:${var.aws_region}:${var.common_services_account}:repository/django_nginx"
    ]
  }

  statement {
    sid    = "Tags"
    effect = "Allow"

    actions = [
      "ec2:DescribeTags",
      "ec2:DescribeInstances"
    ]
    resources = [
      "*"
    ]
  }
}

resource "aws_iam_policy" "portal_server_ecr_policy" {
  name     = "portal_server_ecr"
  path     = "/"
  policy   = data.aws_iam_policy_document.portal_server_ecr_policy.json
}

resource "aws_iam_role_policy_attachment" "portal_server_ecr" {
  role       = aws_iam_role.portal_server.name
  policy_arn = aws_iam_policy.portal_server_ecr_policy.arn
}
