data "local_file" "gotk_components" {
  count    = var.enabled ? 1 : 0
  filename = "${var.flux_system_path}/gotk-components.yaml"
}

data "local_file" "gotk_sync" {
  count    = var.enabled ? 1 : 0
  filename = "${var.flux_system_path}/gotk-sync.yaml"
}

locals {
  rendered_manifest = var.enabled ? join("\n---\n", [
    data.local_file.gotk_components[0].content,
    data.local_file.gotk_sync[0].content,
  ]) : ""
}

resource "local_file" "rendered" {
  count           = var.enabled ? 1 : 0
  filename        = var.output_path
  file_permission = "0640"
  content         = local.rendered_manifest
}

resource "terraform_data" "apply_rendered" {
  count = var.enabled && var.apply_manifests ? 1 : 0

  triggers_replace = {
    rendered_sha256 = sha256(local.rendered_manifest)
  }

  provisioner "local-exec" {
    command = "kubectl apply --server-side -f ${local_file.rendered[0].filename}"
    environment = {
      KUBECONFIG = pathexpand(var.kubeconfig_path)
    }
  }
}
