terraform {
  required_providers {
    sops = {
      source  = "carlpett/sops"
      version = "~> 0.5"
    }
  }
}

variable "name" {
  description = "Name of the volume registration"
  type        = string
}

variable "id" {
  description = "ID to use for the volume registration, defaults to name with - replaced by _"
  type        = string
  default     = null
}

variable "share" {
  description = "Name of the SMB share on the unraid server"
  type        = string
}

variable "subDir" {
  description = "Subdirectory within the SMB share"
  type        = string
  default     = null
}

data "nomad_plugin" "smb" {
  plugin_id        = "smb"
  wait_for_healthy = true
}

data "sops_file" "secrets" {
  source_file = "secrets/secrets.enc.json"
}

resource "nomad_csi_volume_registration" "this" {
  depends_on = [data.nomad_plugin.smb]
  plugin_id  = "smb"

  volume_id   = var.id != null ? var.id : "unraid_${var.share}_${replace(var.name, "-", "_")}"
  name        = var.id != null ? var.id : "unraid_${var.share}_${replace(var.name, "-", "_")}"
  external_id = var.id != null ? var.id : "unraid_${var.share}_${replace(var.name, "-", "_")}"

  capability {
    access_mode     = "single-node-writer"
    attachment_mode = "file-system"
  }

  context = merge({
    source = "//betelgeuse-seven-unraid.lan/${var.share}"
  }, var.subDir == null ? {} : { "subDir" = var.subDir })

  secrets = {
    "username" = "nomad"
    "password" = data.sops_file.secrets.data["unraid.nomad"]
  }
}
