resource "kubernetes_namespace" "samba" {
  metadata {
    name = "samba"
  }
}

resource "kubernetes_service_account" "samba" {

  metadata {
    name      = "samba-sa"
    namespace = kubernetes_namespace.samba.metadata[0].name
  }

  automount_service_account_token = false
}

resource "kubernetes_secret" "samba_secrets" {
  metadata {
    name      = "samba-credentials"
    namespace = kubernetes_namespace.samba.metadata[0].name
  }

  data = {
    USERNAME = var.samba_username
    PASSWORD = var.samba_password
  }
}

resource "kubernetes_deployment" "samba" {
  metadata {
    name      = "samba"
    namespace = kubernetes_namespace.samba.metadata[0].name
    labels = {
      samba = "samba"
    }
  }

  spec {
    replicas = 1

    selector {
      match_labels = {
        samba = "samba"
      }
    }

    strategy {
      type = "Recreate"
    }

    template {
      metadata {
        labels = {
          samba = "samba"
        }
      }

      spec {
        service_account_name            = kubernetes_service_account.samba.metadata[0].name
        automount_service_account_token = false

        container {
          name  = "samba"
          image = "dockurr/samba:${local.samba_version}"


          security_context {
            allow_privilege_escalation = false
          }

          port {
            name           = "smb-1"
            container_port = 445
            host_port      = 445
            protocol       = "TCP"
          }

          port {
            name           = "smb-2"
            container_port = 139
            host_port      = 139
            protocol       = "TCP"
          }

          env {
            name = "USER"
            value_from {
              secret_key_ref {
                name = kubernetes_secret.samba_secrets.metadata[0].name
                key  = "USERNAME"
              }
            }
          }

          env {
            name = "PASS"
            value_from {
              secret_key_ref {
                name = kubernetes_secret.samba_secrets.metadata[0].name
                key  = "PASSWORD"
              }
            }
          }

          volume_mount {
            name       = "storage"
            mount_path = "/storage"
          }
        }

        volume {
          name = "storage"
          host_path {
            path = var.shared_folder
          }
        }
      }
    }
  }

  lifecycle {
    ignore_changes = [spec[0].template[0].metadata[0].annotations["kubectl.kubernetes.io/restartedAt"]]
  }
}

resource "kubernetes_service" "samba" {
  metadata {
    name      = "samba-ports"
    namespace = kubernetes_namespace.samba.metadata[0].name
  }

  spec {
    selector = {
      samba = "samba"
    }

    port {
      name        = "smb"
      port        = 445
      target_port = 445
    }

    type = "LoadBalancer"
  }

  lifecycle {
    ignore_changes = [
      metadata[0].annotations
    ]
  }
}
