resource "random_password" "token" {
  for_each = toset(["manager", "worker"])
  length   = 32
  special  = false
}
data "docker_registry_image" "vigil" {
  name = "valeriansaliou/vigil:${var.vigil_version}"
}
resource "docker_service" "vigil" {
  name = lower(var.vigil_service_name)
  task_spec {
    container_spec {
      image = "${data.docker_registry_image.vigil.name}@${data.docker_registry_image.vigil.sha256_digest}"
      healthcheck {
        #test         = ["CMD-SHELL", "wget -q --no-verbose --tries=1 --spider http://localhost:8080/ || exit 1"]
        #interval     = "10s"
        #timeout      = "10s"
        #retries      = 3
        #start_period = "1m"
        # Disable healtcheck
        test = ["NONE"]
      }
      configs {
        config_id   = docker_config.vigil.id
        config_name = docker_config.vigil.name
        file_name   = "/etc/vigil.cfg"
      }
    }
    dynamic "networks_advanced" {
      for_each = var.docker_networks
      content {
        name = networks_advanced.value.id
      }
    }
    restart_policy {
      condition = "any"
      delay     = "20s"
      window    = "0s"
    }
  }
  #converge_config {
  #  delay   = "5s"
  #  timeout = "2m"
  #}
  update_config {
    order       = "stop-first"
    parallelism = 1
  }
  endpoint_spec {
    ports {
      target_port  = 8080
      publish_mode = "ingress"
    }
  }
}
resource "random_id" "vigil_iter" {
  byte_length = 4
  keepers = {
    checksum = local.vigil_toml_checksum
  }
}
resource "docker_config" "vigil" {
  name = lower(join("-", [var.vigil_service_name, random_id.vigil_iter.hex]))
  data = sensitive(base64encode(local.vigil_toml)) // I have marked this as sensitive just so it wont spam the hell out of the terminal with a wall of text. Its not actually sensitive.
  lifecycle {
    ignore_changes        = [name]
    create_before_destroy = true
  }
}