job "traefik-consul-lb" {
  datacenters = ["dc1"]
  type = "service"

  group "traefik" {
    count = 1

    constraint {
      attribute = "${node.unique.name}"
      value     = "hcp1"
    }

    update {
      min_healthy_time  = "60s"
      healthy_deadline  = "5m"
      progress_deadline = "10m"
      auto_revert       = false
    }

    network {
      mode = "host"
      port "http" {
        static = 80
        host_network = "tailscale0"
      }
      port "traefik" {
        static = 8080
        host_network = "tailscale0"
      }
    }

    task "traefik" {
      driver = "exec"
      
      config {
        command = "/usr/local/bin/traefik"
        args = [
          "--configfile=/local/traefik.yml"
        ]
      }

      template {
        data = <<EOF
api:
  dashboard: true
  insecure: true

entryPoints:
  web:
    address: "100.97.62.111:80"
  traefik:
    address: "100.97.62.111:8080"

providers:
  file:
    filename: /local/dynamic.yml
    watch: true

metrics:
  prometheus:
    addEntryPointsLabels: true
    addServicesLabels: true
    addRoutersLabels: true

log:
  level: INFO
EOF
        destination = "local/traefik.yml"
      }

      template {
        data = <<EOF
http:
  middlewares:
    consul-stripprefix:
      stripPrefix:
        prefixes:
          - "/consul"
    
    traefik-stripprefix:
      stripPrefix:
        prefixes:
          - "/traefik"

  services:
    consul-cluster:
      loadBalancer:
        servers:
          - url: "http://warden.tailnet-68f9.ts.net:8500"  # 北京，优先
          - url: "http://ch4.tailnet-68f9.ts.net:8500"     # 韩国，备用
          - url: "http://ash3c.tailnet-68f9.ts.net:8500"   # 美国，备用
        healthCheck:
          path: "/v1/status/leader"
          interval: "30s"
          timeout: "15s"

  routers:
    consul-api:
      rule: "PathPrefix(`/consul`)"
      service: consul-cluster
      middlewares:
        - consul-stripprefix
      entryPoints:
        - web
    
    traefik-dashboard:
      rule: "PathPrefix(`/traefik`)"
      service: dashboard@internal
      middlewares:
        - traefik-stripprefix
      entryPoints:
        - web
EOF
        destination = "local/dynamic.yml"
      }

      resources {
        cpu = 500
        memory = 512
      }

      service {
        name = "consul-lb"
        port = "http"
        
        check {
          name     = "consul-lb-health"
          type     = "http"
          path     = "/consul/v1/status/leader"
          interval = "30s"
          timeout  = "5s"
        }
      }

      service {
        name = "traefik-dashboard"
        port = "traefik"
        
        check {
          name     = "traefik-dashboard-health"
          type     = "http"
          path     = "/api/rawdata"
          interval = "30s"
          timeout  = "5s"
        }
      }

    }
  }
}
