variable "image_tag" {
  type        = string
  description = "Docker image tag to deploy."
  default     = "latest"
}

job "torsearch" {
  datacenters = [ "home" ]
  type = "service"

  group "app" {
    count = 2

    update {
      max_parallel     = 4
      min_healthy_time = "30s"
      healthy_deadline = "3m"
      auto_revert = true
    }

    network {
      port "app" {
        to = 80
      }
    }

    task "app" {
      driver = "docker"

      config {
        image = "registry.caldwell.digital/home/torsearch-app:${var.image_tag}"
        ports = ["app"]
      }

      env {
        MERCURE_PUBLISHER_JWT_KEY = "!ChangeThisMercureHubJWTSecretKey!"
        MERCURE_SUBSCRIBER_JWT_KEY = "!ChangeThisMercureHubJWTSecretKey!"
      }

      service {
        name = "torsearch-app"
        provider = "nomad"
        port = "app"

        meta {
          nomad_ingress_enabled  = true
          nomad_ingress_hostname = "torsearch-nomad.caldwell.digital"
        }
      }
    }
  }

  group "worker" {
    count = 2
    update {
      max_parallel     = 4
      min_healthy_time = "30s"
      healthy_deadline = "3m"
      auto_revert = true
    }

    volume "media" {
      type = "host"
      source = "media"
      read_only = false
    }

    task "worker" {
      driver = "docker"

      volume_mount {
        volume      = "media"
        destination = "/var/download"
        read_only = false
      }

      config {
        image = "registry.caldwell.digital/home/torsearch-worker:${var.image_tag}"
        args = [
          "-vv"
        ]
      }

      service {
        name = "torsearch-worker"
        provider = "nomad"
      }
    }
  }

  group "scheduler" {
    count = 1

    update {
      max_parallel     = 2
      min_healthy_time = "30s"
      healthy_deadline = "3m"
      auto_revert = true
    }

    volume "media" {
      type = "host"
      source = "media"
      read_only = false
    }

    task "scheduler" {
      driver = "docker"

      volume_mount {
        volume      = "media"
        destination = "/var/download"
        read_only = false
      }

      config {
        image = "registry.caldwell.digital/home/torsearch-scheduler:${var.image_tag}"
        args = [
          "-vv"
        ]
      }

      service {
        name = "torsearch-scheduler"
        provider = "nomad"
      }
    }
  }
}