# Use prod AWS account to store state
terraform {
  backend "s3" {
    bucket  = "orcd-terraform-state"
    key     = "gcp/prisma-cloud-integration/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

provider "random" {}

provider "google" {}

resource "random_string" "unique_id" {
  special   = false
  length    = 5
  min_lower = 5
}

resource "google_service_account" "prisma_cloud_service_account" {
  account_id   = "prisma-cloud-serv-${random_string.unique_id.result}"
  project      = var.project_id
  display_name = "Prisma Cloud Service Account"
}

resource "google_organization_iam_custom_role" "prisma_cloud_organization_custom_role" {
  role_id     = "prismaCloudViewer${random_string.unique_id.result}"
  org_id      = var.org_id
  permissions = var.org_iam_policy_custom_role_permissions
  description = "This is a custom role created for Prisma Cloud. Contains granular additional permission which is not covered by built-in roles"
  title       = "Prisma Cloud Viewer ${random_string.unique_id.result}"
}

/* Avoid storing keys in state
resource "google_service_account_key" "prisma_cloud_service_account_key" {
  service_account_id = google_service_account.prisma_cloud_service_account.name
}

resource "local_file" "key" {
  filename = "${var.project_id}-${random_string.unique_id.result}.json"
  content  = base64decode(google_service_account_key.prisma_cloud_service_account_key.private_key)
} */

resource "google_project_service" "project_apis" {
  service            = var.project_services[count.index]
  disable_on_destroy = false
  count              = length(var.project_services)
  project            = var.project_id
}

resource "google_project_service" "org_onboarding_apis" {
  service = var.org_services[count.index]
  count   = length(var.org_services)
  project = var.project_id
}

resource "google_organization_iam_member" "bind_custom_role_to_org_iam_policy" {
  role   = "organizations/${var.org_id}/roles/${google_organization_iam_custom_role.prisma_cloud_organization_custom_role.role_id}"
  org_id = var.org_id
  member = "serviceAccount:${google_service_account.prisma_cloud_service_account.email}"
}

resource "google_organization_iam_member" "bind_managed_roles_to_org_iam_policy" {
  role   = var.org_iam_policy_managed_roles[count.index]
  org_id = var.org_id
  count  = length(var.org_iam_policy_managed_roles)
  member = "serviceAccount:${google_service_account.prisma_cloud_service_account.email}"
}




