job "postgres" {
  group "postgres" {
    service {
      name = "postgres"
      port = "db"

      connect {
        sidecar_service {}
      }
    }

    task "postgres" {
      driver = "docker"

      config {
        # Temporarily pin to v17 as v18 moved the default data directory and immich doesn't officially support it yet
        # immich also needs >= 0.3.0, < 0.5.0. https://docs.immich.app/administration/postgres-standalone/#prerequisites
        #image = "postgres:17"  
        image = "tensorchord/vchord-postgres:pg17-v0.4.3"
        ports = ["db"]

        volumes = [
          "secrets/postgres_password:/run/secrets/postgres_password"
        ]
      }

      volume_mount {
        volume      = "data"
        destination = "/var/lib/postgresql/data"
        read_only   = false
      }

      env {
        POSTGRES_USER          = "postgres"
        POSTGRES_PASSWORD_FILE = "/run/secrets/postgres_password"
        POSTGRES_INITDB_ARGS   = "--auth-host=md5"
      }

      resources {
        cpu    = 500
        memory = 1024
      }

      template {
        # This securely sets the initial password for the postgres user, to change it later
        # you need to connect to the database and change it manually
        data        = <<EOF
{{ with nomadVar "nomad/jobs/postgres" }}{{ .postgres_password }}{{ end }}
EOF
        destination = "secrets/postgres_password"
      }
    }

    network {
      mode = "bridge"
      port "db" {
        static = 5432
      }
    }

    volume "data" {
      type      = "host"
      read_only = false
      source    = "postgres"
    }
  }
}
