module "ows_timed_release_secrets_manager_policy" {
  source = "git@github.com:theorchard/terraform-iam-policy-templates.git//documents/secretsmanager/secrets_list?ref=0.3.0"

  secrets = [
    "${var.environment}/${var.service_name}/RDS_MYSQL_USER",
    "${var.environment}/${var.service_name}/RDS_MYSQL_PASSWORD"
  ]
  action_types = ["read"]

  depends_on = [
    module.secrets,
  ]
}

resource "aws_iam_policy" "ows_timed_release_secrets_manager_policy" {
  name   = "SecretsManager-${var.environment}-${var.service_name}-integration-test-policy"
  policy = module.ows_timed_release_secrets_manager_policy.policy.json
}

data "aws_iam_role" "pipeline_agent_role" {
  name = "prod-jenkins-aws-pipeline-agent"
}

data "aws_iam_policy_document" "jenkins_assume_role_policy" {
  version = "2012-10-17"
  statement {
    actions = ["sts:AssumeRole"]
    effect  = "Allow"
    principals {
      type = "AWS"

      identifiers = [
        data.aws_iam_role.pipeline_agent_role.arn,
      ]
    }
  }
}

resource "aws_iam_role" "ows_timed_release_role" {
  name = "${var.environment}-${var.service_name}-integration-test-role"

  assume_role_policy = data.aws_iam_policy_document.jenkins_assume_role_policy.json
}

resource "aws_iam_role_policy_attachment" "ows_timed_release_role_policy_attachment" {
  role       = aws_iam_role.ows_timed_release_role.name
  policy_arn = aws_iam_policy.ows_timed_release_secrets_manager_policy.arn
}

module "ows_timed_release_owsrequest" {
  source           = "git@github.com:theorchard/terraform-owsrequest.git//?ref=1.0.1"
  environment_name = var.environment
  service_name     = var.service_name
}

# Attach Dynamo qa-ows-request-authorization policy to integration test role.
resource "aws_iam_role_policy_attachment" "qa-ows-request-authorization-dynamo-policy_attachment" {
  role       = aws_iam_role.ows_timed_release_role.name
  policy_arn = module.ows_timed_release_owsrequest.policy_arn_output
}
