provider "github" {
  owner = var.github_organization
  app_auth {}
}

data "aws_secretsmanager_secret_version" "github_webhook_secret" {
  secret_id = aws_secretsmanager_secret.atlantis_secret["GH_WEBHOOK_SECRET"].id
}

data "github_repository" "repositories" {
  for_each  = toset(var.github_repositories)
  full_name = each.value
}

# If the GH_WEBHOOK_SECRET secret has not been updated since creation when this is applied, the value will be "dummy".
# As such, please update the secret value and apply this resource once more, which should update the hook in place.
resource "github_repository_webhook" "atlantis" {
  for_each   = toset(var.github_repositories)
  repository = data.github_repository.repositories[each.value].name
  active     = true

  configuration {
    url          = "https://${var.atlantis_service_fqdn}/events"
    content_type = "json"
    insecure_ssl = false
    secret       = data.aws_secretsmanager_secret_version.github_webhook_secret.secret_string
  }

  events = [
    "issue_comment",
    "pull_request",
    "pull_request_review",
    "push",
  ]
}
