resource "aws_iam_instance_profile" "jira_server_instance_profile" {
  name     = "jira-server-instance-profile"
  role     = aws_iam_role.jira_server.name
}

resource "aws_iam_role" "jira_server" {
  name     = "jira-server-instance-role"
  path     = "/instance/"

  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" "jira_server_ecr_policy" {
  statement {
    actions = [
      "ecr:GetAuthorizationToken",
    ]

    resources = ["*"]
  }

  statement {
    sid    = "AllowCluCommunicationECR"
    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:us-east-1:${var.aws_account_id}:repository/*"
    ]
  }

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

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

resource "aws_iam_policy" "jira_server_ecr_policy" {
  name     = "jira-server"
  path     = "/instance/"
  policy   = data.aws_iam_policy_document.jira_server_ecr_policy.json
}

resource "aws_iam_role_policy_attachment" "jira_server_ecr" {
  role       = aws_iam_role.jira_server.name
  policy_arn = aws_iam_policy.jira_server_ecr_policy.arn
}

resource "aws_iam_role_policy_attachment" "jira_splunk_sh_AmazonEC2RoleforSSM" {
  role       = aws_iam_role.jira_server.name
  policy_arn = "arn:${var.aws_partition}:iam::aws:policy/service-role/AmazonEC2RoleforSSM"
}

resource "aws_iam_role_policy_attachment" "jira_splunk_sh_policy_attach_tag_read" {
  role       = aws_iam_role.jira_server.name
  policy_arn = "arn:${var.aws_partition}:iam::${var.aws_account_id}:policy/launchroles/default_instance_tag_read"
}

resource "aws_iam_role_policy_attachment" "jira_splunk_sh_policy_attach_cloudwatch" {
  role       = aws_iam_role.jira_server.name
  policy_arn = "arn:${var.aws_partition}:iam::${var.aws_account_id}:policy/cloudwatch_events"
}

#This policy needs to be create prior to creating the Salt Master
resource "aws_iam_role_policy_attachment" "jira_splunk_sh_policy_attach_binaries" {
  role       = aws_iam_role.jira_server.name
  policy_arn = "arn:${var.aws_partition}:iam::${var.aws_account_id}:policy/launchroles/default_instance_s3_binaries"
}
