job "openreader" {
  group "openreader" {
    network {
      mode = "bridge"
      port "http" {
        to = 3003
      }
    }

    # Consul Connect sidecar with upstream to postgres
    service {
      connect {
        sidecar_service {
          proxy {
            upstreams {
              destination_name = "postgres"
              local_bind_port  = 5432
            }
          }
        }
      }
    }

    service {
      name = "openreader"
      port = "http"

      tags = [
        "traefik.enable=true",
        "traefik.http.routers.openreader.middlewares=auth@file",
      ]

      check {
        type     = "http"
        path     = "/"
        interval = "10s"
        timeout  = "2s"
      }
    }

    service {
      name         = "openreader-api"
      port         = "http"
      address_mode = "alloc" # Use allocation IP for Connect as the sidecar can't access the host's published port (hairpin/loopback NAT issue)

      connect {
        sidecar_service {}
      }

      check {
        type     = "http"
        path     = "/"
        interval = "10s"
        timeout  = "2s"
      }
    }

    task "openreader" {
      driver = "docker"

      config {
        image = "ghcr.io/richardr1126/openreader:v2.1.2"
        ports = ["http"]
      }

      env = {
        TZ = "Australia/Melbourne"

        # Use embedded SeaweedFS for blob storage (data lives in /app/docstore/seaweedfs).
        # Port 8333 is not exposed; browser uploads/downloads fall back through the app API.
        USE_EMBEDDED_WEED_MINI = "true"
        S3_ENDPOINT            = "http://localhost:8333"
        S3_FORCE_PATH_STYLE    = "true"

        # Auth is intentionally disabled (no BASE_URL / AUTH_SECRET set).
        # Access is controlled by the Authelia middleware on the Traefik router above.

        # To enable server-side library import from an Unraid share, add a second CSI volume
        # mount for the share (e.g. unraid_media_books → /app/docstore/library:ro) and set:
        #   IMPORT_LIBRARY_DIR = "/app/docstore/library"
      }

      template {
        data        = <<EOF
POSTGRES_URL=postgresql://openreader:{{ with nomadVar "nomad/jobs/openreader" }}{{ .database_pw }}{{ end }}@localhost:5432/openreader
EOF
        destination = "secrets/openreader.env"
        env         = true
      }

      volume_mount {
        volume      = "unraid_appdata_openreader"
        destination = "/app/docstore"
        read_only   = false
      }

      resources {
        cpu        = 200
        memory     = 750
        memory_max = 1024
      }
    }

    volume "unraid_appdata_openreader" {
      type            = "csi"
      read_only       = false
      source          = "unraid_appdata_openreader"
      access_mode     = "single-node-writer"
      attachment_mode = "file-system"

      mount_options {
        mount_flags = ["uid=1000", "gid=1000"]
      }
    }
  }
}
