data "docker_registry_image" "minio" {
  name = "quay.io/minio/minio:latest"
}

resource "random_password" "minio_password" {
  length  = 32
  special = false
}

locals {
  SERVER_URL = "http://${var.domain}"
  UI_URL     = "http://${var.domain}/ui/"
}

resource "docker_service" "minio" {
  name = "minio"
  task_spec {
    container_spec {
      image   = "${data.docker_registry_image.minio.name}@${data.docker_registry_image.minio.sha256_digest}"
      command = ["minio", "server", "/data", ]
      env = {
        MINIO_ADDRESS              = "0.0.0.0:9000"
        MINIO_CONSOLE_ADDRESS      = "0.0.0.0:9001"
        MINIO_ROOT_USER            = var.admin_username
        MINIO_ROOT_PASSWORD        = random_password.minio_password.result
        MINIO_SERVER_URL           = local.SERVER_URL
        MINIO_BROWSER_REDIRECT_URL = local.UI_URL
        MINIO_BROWSER_REDIRECT     = true
        MINIO_API_ROOT_ACCESS      = "on"
      }
      mounts {
        target    = "/data"
        source    = var.storage_path
        type      = "bind"
        read_only = false
      }
    }
    networks_advanced {
      name = var.network.id
    }
    placement {
      platforms {
        architecture = "amd64"
        os           = "linux"
      }
    }
  }
  update_config {
    parallelism = 1
    order       = "stop-first"
  }
}

module "minio_nginx_config" {
  source   = "git::https://code.techinc.nl/grey/terraform-nginx.git//nginx-site-available"
  hostname = var.domain
  //certificate   = acme_certificate.ooo_grey["s3"]
  service_name  = "minio_s3"
  upstream_host = "${docker_service.minio.name}:9000"
  config_prefix = "nginx"
  extra_upstreams = [
    {
      name    = "minio_ui",
      servers = ["${docker_service.minio.name}:9001"]
    }
  ]
  extra_locations = file("${path.module}/minio_nginx_extra.conf")
  allow_non_ssl   = true
  allow_ssl       = false
}