module "grafanaclient" {
  source = "./modules/kc-client"

  realm           = var.realm
  client_id       = "grafana"
  client_name     = "Grafana"
  client_secret   = var.grafana_secret
  description     = "https://grafana.tobiasmanske.de"
  admin_role_name = "serveradmin"

  root_url            = "https://grafana.tobiasmanske.de"
  admin_url           = "https://grafana.tobiasmanske.de"
  base_url            = "https://grafana.tobiasmanske.de"
  valid_redirect_uris = ["https://grafana.tobiasmanske.de/*"]
  web_origins         = ["https://grafana.tobiasmanske.de"]
}

resource "keycloak_openid_group_membership_protocol_mapper" "grafana-membership-mapper" {
  realm_id  = module.grafanaclient.realm.id
  client_id = module.grafanaclient.client.id

  name                = "Group Mapper"
  claim_name          = "groups"
  full_path           = false
  add_to_userinfo     = true
  add_to_access_token = false
  add_to_id_token     = true
}

resource "keycloak_openid_user_property_protocol_mapper" "grafana-username-mapper" {
  realm_id  = module.grafanaclient.realm.id
  client_id = module.grafanaclient.client.id

  name                = "username"
  user_property       = "username"
  claim_name          = "preferred_username"
  add_to_userinfo     = true
  add_to_access_token = true
  add_to_id_token     = false
}

resource "keycloak_openid_user_client_role_protocol_mapper" "grafana-role-mapper" {
  realm_id            = module.grafanaclient.realm.id
  client_id           = module.grafanaclient.client.id
  multivalued         = true
  name                = "user-client-role-mapper"
  claim_name          = "resource_access.$${client_id}.roles"
  add_to_userinfo     = true
  add_to_access_token = true
  add_to_id_token     = false
}

resource "keycloak_role" "grafana-admin" {
  realm_id    = module.grafanaclient.realm.id
  client_id   = module.grafanaclient.client.id
  name        = "admin"
  description = "Admin"
}
resource "keycloak_role" "grafana-editor" {
  realm_id    = module.grafanaclient.realm.id
  client_id   = module.grafanaclient.client.id
  name        = "editor"
  description = "Editor"
}
resource "keycloak_role" "grafana-viewer" {
  realm_id    = module.grafanaclient.realm.id
  client_id   = module.grafanaclient.client.id
  name        = "viewer"
  description = "Viewer"
}