# Install Rancher helm chart
resource "helm_release" "rancher_server" {
  depends_on = [var.wait_on]

  name             = "rancher"
  chart            = "${var.rancher_helm_repository}/rancher-${var.rancher_version}.tgz"
  namespace        = "cattle-system"
  create_namespace = true
  wait             = true

  values = [file("${path.module}/rancher-values.yaml")]

  set = [{
    name = "hostname"
    value = join(".", ["rancher", var.server_dns])
  },

  {
    name  = "bootstrapPassword"
    value = "admin" # TODO: change this once the terraform provider has been updated with the new pw bootstrap logic
  }]
}

resource "random_password" "admin_password" {
  length           = 32
  special          = true
  override_special = "_%@"
}

# Initialize Rancher server
resource "rancher2_bootstrap" "admin" {
  depends_on = [
    helm_release.rancher_server
  ]

  provider = rancher2.bootstrap

  password  = random_password.admin_password.result
  telemetry = true
}

resource "rancher2_cluster_sync" "admin" {
  provider = rancher2.admin

  cluster_id = "local"
}

output "rancher_uri" {
  value = "https://${local.rancher_server_dns}"
}

output "rancher_server_admin_password" {
  value = random_password.admin_password.result
  sensitive = true
}

output "rancher_server_admin_token" {
  value     = rancher2_bootstrap.admin.token
  sensitive = true
}

output "installed" {
  value = true
  depends_on = [helm_release.rancher_server]
}
