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

variable "name" {
  description = "Name of the application, also used as subdir on the unraid appdata share"
  type        = string
}

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

variable "access_mode" {
  description = "CSI volume access mode"
  type        = string
  default     = "single-node-writer"
  validation {
    condition     = contains(["single-node-writer", "multi-node-multi-writer"], var.access_mode)
    error_message = "access_mode must be either 'single-node-writer' or 'multi-node-multi-writer'"
  }
}

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_appdata_${replace(var.name, "-", "_")}"
  name        = var.id != null ? var.id : "unraid_appdata_${replace(var.name, "-", "_")}"
  external_id = var.id != null ? var.id : "unraid_appdata_${replace(var.name, "-", "_")}"

  capability {
    access_mode     = var.access_mode
    attachment_mode = "file-system"
  }

  context = {
    source = "//betelgeuse-seven-unraid.lan/appdata"
    subDir = var.name
  }

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