
# Set up a Pub/Sub topic and subscription
resource "google_pubsub_topic" "this" {
  name = "gsirt-logs"

  labels = {
    plat_env_project_service = "dph_common_sec_pubsub"
  }
}

resource "google_pubsub_subscription" "this" {
  name  = "gsirt-logs-pull"
  topic = google_pubsub_topic.this.id
}

# Configure the logging export
resource "google_logging_project_sink" "this" {
  name        = "gsirt-sink"
  description = "Export logs to Splunk via Pub/Sub"

  destination = "pubsub.googleapis.com/${google_pubsub_topic.this.id}"

  filter = "logName:\"/logs/cloudaudit.googleapis.com\""

  unique_writer_identity = false
}

# Set IAM policy permissions for the Pub/Sub topic
resource "google_pubsub_topic_iam_binding" "this" {
  members = [google_logging_project_sink.this.writer_identity]
  role    = "roles/pubsub.publisher"
  topic   = google_pubsub_topic.this.id
}

# Allow Splunk pull logs using Splunk Add-on for Google Cloud Platform
resource "google_service_account" "this" {
  account_id   = "gsirt-logs-export"
  display_name = "gsirt-logs-export"
  description  = "Export logs to Splunk"
}

resource "google_project_iam_member" "this_viewer" {
  member  = "serviceAccount:${google_service_account.this.email}"
  project = var.project_id
  role    = "roles/pubsub.viewer"
}

resource "google_project_iam_member" "this_subscriber" {
  member  = "serviceAccount:${google_service_account.this.email}"
  project = var.project_id
  role    = "roles/pubsub.subscriber"
}
