# ABOUTME: Nomad job for AnimalTrack - poultry farm management app.
# ABOUTME: Runs FastHTML Python app with SQLite, behind Traefik with OIDC auth.

# Setup required before running:
#   sudo mkdir -p /data/services/animaltrack && sudo chown 1000:1000 /data/services/animaltrack
#   nomad var put secrets/animaltrack csrf_secret="$(nix shell nixpkgs#openssl -c openssl rand -base64 32)"

job "animaltrack" {
  datacenters = ["alo"]

  # Force re-pull of :latest images on each nomad run
  meta {
    uuid = uuidv4()
  }

  update {
    max_parallel      = 1
    health_check      = "checks"
    min_healthy_time  = "30s"
    healthy_deadline  = "5m"
    progress_deadline = "10m"
    auto_revert       = true
  }

  group "web" {
    network {
      port "http" {
        to = 3366
      }
    }

    task "app" {
      driver = "docker"
      user   = "1000"

      config {
        image      = "gitea.v.paler.net/alo/animaltrack:latest"
        ports      = ["http"]
        force_pull = true
        volumes    = ["/data/services/animaltrack:/var/lib/animaltrack"]
      }

      env {
        DB_PATH           = "/var/lib/animaltrack/animaltrack.db"
        AUTH_HEADER_NAME  = "X-Oidc-Username"
        SEED_ON_START     = "true"
        TRUSTED_PROXY_IPS = "192.168.1.0/24"
      }

      # Template needed for nomadVar interpolation (secrets)
      template {
        destination = "secrets/env.env"
        env         = true
        data        = <<EOH
CSRF_SECRET={{ with nomadVar "secrets/animaltrack" }}{{ .csrf_secret }}{{ end }}
EOH
      }

      resources {
        memory = 512
      }

      service {
        name = "animaltrack"
        port = "http"

        tags = [
          "traefik.enable=true",
          "traefik.http.routers.animaltrack.entryPoints=websecure",
          "traefik.http.routers.animaltrack.middlewares=oidc-auth@file",
          "traefik.http.routers.animaltrack.rule=Host(`farm.alo.land`)",
        ]

        check {
          type     = "http"
          path     = "/healthz"
          interval = "10s"
          timeout  = "5s"

          check_restart {
            limit = 3
            grace = "60s"
          }
        }
      }
    }
  }
}
