terraform {
  required_providers {
    null = {
      source  = "hashicorp/null"
      version = "3.2.2"
    }
  }
}
resource "kubernetes_namespace" "vault" {
  depends_on = [var.wait_on]

  metadata {
    name = var.namespace
  }

  lifecycle {
    ignore_changes = [metadata]
  }
}

resource "kubernetes_secret" "vault" {
  metadata {
    name      = "vault-aws-creds"
    namespace = kubernetes_namespace.vault.metadata.0.name
  }

  data = {
    AWS_ACCESS_KEY_ID     = var.aws.access_key_id
    AWS_SECRET_ACCESS_KEY = var.aws.secret_access_key
  }
}

resource "helm_release" "vault" {
  depends_on = [kubernetes_secret.vault]
  name             = "vault"
  repository       = "https://helm.releases.hashicorp.com"
  chart            = "vault"
  namespace        = var.namespace
  version          = "0.28.1"
  create_namespace = false
  wait             = true

  set = [{
    name  = "server.ha.enabled"
    value = "false"
  },
  {
    name  = "server.ha.replicas"
    value = "1"
  },
  {
    name  = "server.ha.raft.enabled"
    value = "false"
  }]

  values = [
    templatefile("${path.module}/values.yaml.tftpl", {
      service_uri = local.service_uri,
      ingress     = var.ingress,
      aws         = var.aws,
    })
  ]
}

resource "null_resource" "vault_init" {
  provisioner "local-exec" {
    command = <<-EOT
      OUTPUT=$(kubectl exec -n ${kubernetes_namespace.vault.metadata.0.name} ${local.vault_pod_name} -- vault operator init -format=json)
      echo "$OUTPUT" > "${local.vault_keys_file}"
    EOT

    environment = {
      KUBECONFIG = var.k8s_config_path
    }
  }
}

output "installed" {
  depends_on = [null_resource.vault_init]
  value = true
}
