# Provision the Microsoft Entra ID app registration, client secret, groups
# claim, and security groups for Teleport Enterprise OIDC SSO.
# Protect Terraform state as a secret because it contains the client secret.

terraform {
  required_version = ">= 1.3"

  required_providers {
    azuread = {
      source  = "hashicorp/azuread"
      version = ">= 2.47, < 4.0"
    }
  }
}

variable "proxy_public_addr" {
  description = "Public Teleport Proxy hostname with no scheme or path, for example teleport.example.com"
  type        = string
}

variable "tenant_id" {
  description = "Microsoft Entra ID tenant ID (UUID). Leave empty to use the active az login tenant."
  type        = string
  default     = ""
}

variable "app_display_name" {
  description = "Display name of the Entra ID application registration"
  type        = string
  default     = "Teleport Access"
}

variable "client_secret_lifetime" {
  description = "Validity period for the client secret (Entra caps this at 24 months / 17520h)"
  type        = string
  default     = "8760h"
}

variable "group_names" {
  description = "Entra security group display names to create (map their output Object IDs in claims_to_roles)"
  type        = list(string)
  default     = ["Teleport-Admins", "Teleport-Developers"]
}

provider "azuread" {
  tenant_id = var.tenant_id != "" ? var.tenant_id : null
}

data "azuread_client_config" "current" {}

resource "azuread_group" "groups" {
  for_each = toset(var.group_names)

  display_name     = each.key
  security_enabled = true
}

resource "azuread_application" "this" {
  display_name            = var.app_display_name
  sign_in_audience        = "AzureADMyOrg"
  group_membership_claims = ["SecurityGroup"]

  web {
    redirect_uris = ["https://${var.proxy_public_addr}/v1/webapi/oidc/callback"]
  }

  optional_claims {
    id_token {
      name      = "groups"
      essential = true
    }
  }
}

resource "azuread_service_principal" "this" {
  client_id = azuread_application.this.client_id
}

resource "azuread_application_password" "this" {
  application_id    = azuread_application.this.id
  display_name      = var.app_display_name
  end_date_relative = var.client_secret_lifetime
}

locals {
  tenant_id = var.tenant_id != "" ? var.tenant_id : data.azuread_client_config.current.tenant_id
}

output "tenant_id" {
  description = "Directory (tenant) ID"
  value       = local.tenant_id
}

output "application_id" {
  description = "Application (client) ID"
  value       = azuread_application.this.client_id
}

output "client_secret" {
  description = "Client secret value for the Teleport OIDC connector"
  value       = azuread_application_password.this.value
  sensitive   = true
}

output "group_object_ids" {
  description = "Map of group display names to immutable Object IDs for claims_to_roles"
  value = {
    for name, group in azuread_group.groups : name => group.object_id
  }
}
