job "blaaai" {
  region      = "global"
  datacenters = ["dc1"]
  type        = "service"

  meta {
    uuid        = uuidv4()
  }

  update {
    stagger           = "30s"
    max_parallel      = 1
    auto_revert       = true
    progress_deadline = "25m"
  }

  group "blaaai-group" {
    count = 1

    constraint {
      attribute = "${node.unique.name}"
      value     = "autobox.i80.dk"
    }

    update {
      canary           = 1
      auto_promote     = true
      min_healthy_time = "15s"
      healthy_deadline = "20m"
      progress_deadline = "25m"
      auto_revert      = true
    }

    network {
      port "http" {}
    }

    reschedule {
      attempts       = 5
      interval       = "10m"
      delay          = "30s"
      delay_function = "exponential"
      max_delay      = "120s"
      unlimited      = false
    }

    volume "blaaai-data" {
      type      = "host"
      source    = "blaaai-data"
      read_only = false
    }

    service {
      provider = "consul"
      name     = "blaaai"
      port     = "http"

      tags = [
        "traefik.enable=true",
        "traefik.http.routers.blaaai.rule=Host(`blaaai.i80.dk`)",
        "traefik.http.routers.blaaai.tls=true",
      ]

      canary_tags = [
        "traefik.enable=false",
      ]

      check {
        name     = "http_health_check"
        type     = "http"
        port     = "http"
        path     = "/health"
        interval = "10s"
        timeout  = "5s"
      }
    }

    task "blaaai-task" {
      driver = "docker"

      config {
        image      = "registry.i80.dk/gitea/blaaai:latest"
        ports      = ["http"]
        force_pull = true
        auth {
          username = "robot$gitserver"
          password = "${HARBOR_ROBOT_TOKEN}"
        }
      }

      volume_mount {
        volume      = "blaaai-data"
        destination = "/app/data"
        read_only   = false
      }

      restart {
        attempts = 10
        interval = "10m"
        delay    = "15s"
        mode     = "fail"
      }

      env {
        PORT = "${NOMAD_PORT_http}"
      }

      template {
        data        = <<EOT
ANTHROPIC_API_KEY={{ key "blaaai/anthropic_api_key" }}
HARBOR_ROBOT_TOKEN={{ key "blaaai/harbor_robot_token" }}
EOT
        destination = "secrets/app.env"
        env         = true
      }

      resources {
        cpu    = 500
        memory = 512
      }
    }
  }
}
