job "pgadmin" {
  group "pgadmin" {
    service {
      connect {
        sidecar_service {
          proxy {
            upstreams {
              destination_name = "postgres"
              local_bind_port  = 5432
            }
          }
        }
      }
    }

    network {
      mode = "bridge"
      port "http" {
        to = 80
      }
    }

    task "pgadmin" {
      driver = "docker"

      config {
        image = "dpage/pgadmin4:latest"
        ports = ["http"]

        volumes = [
          "local/servers.json:/pgadmin4/servers.json",
          "secrets/.pgpass:/home/.pgpass"
        ]
      }

      env = {
        PGADMIN_DEFAULT_EMAIL                     = "othrayte@gmail.com"
        PGADMIN_DEFAULT_PASSWORD                  = "admin"
        PGADMIN_CONFIG_WTF_CSRF_ENABLED           = "False"
        PGADMIN_CONFIG_WTF_CSRF_CHECK_DEFAULT     = "False"
        PGADMIN_CONFIG_ENHANCED_COOKIE_PROTECTION = "False"
        PGADMIN_CONFIG_SERVER_MODE                = "False"
        PGADMIN_CONFIG_MASTER_PASSWORD_REQUIRED   = "False"
      }

      resources {
        cpu    = 500
        memory = 256
      }

      service {
        name = "pgadmin"
        port = "http"

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

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

      template {
        data        = <<EOF
{
  "Servers": {
    "1": {
      "Group": "Servers",
      "Name": "postgres",
      "Host": "localhost",
      "Port": 5432,
      "MaintenanceDB": "postgres",
      "Username": "postgres",
      "PassFile": "/home/.pgpass"
    }
  }
}
EOF
        destination = "local/servers.json"
      }

      template {
        data        = <<EOF
localhost:5432:*:postgres:{{ with nomadVar "nomad/jobs/postgres" }}{{ .postgres_password }}{{ end }}
EOF
        destination = "secrets/.pgpass"
        perms       = "0400"
        uid         = 5050 # pgadmin
      }
    }
  }
}
