job "postgres-server" {
  datacenters = ["dc1"]
  type = "service"
  priority = 80

  group "postgres-server" {
    count = 1

    restart {
      attempts = 10
      interval = "5m"
      delay = "25s"
      mode = "delay"
    }

    network {
      mode = "bridge"

      port "db" {
        static = 5432
      }

      port "tls" {}
    }

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

    service {
      name = "postgres-server"
      provider = "nomad"
      port = "db"
    }

    service {
      name = "postgres-tls"
      provider = "nomad"
      port = "tls"
    }

    task "postgres-server" {
      driver = "docker"

      config {
        image = "postgres:14"
        ports = ["db"]
      }

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

      env = {
        # Allow connections from any host
        "MYSQL_ROOT_HOST" = "%"
      }

      template {
        data = <<EOH
{{ with nomadVar "nomad/jobs/postgres-server" }}
POSTGRES_USER={{ .superuser }}
POSTGRES_PASSWORD={{ .superuser_pass }}
{{ end }}
        EOH
        destination = "secrets/db.env"
        env = true
      }

      resources {
        cpu = 500
        memory = 700
        memory_max = 1200
      }
    }

    task "stunnel" {
      driver = "docker"

      config {
        image = "iamthefij/stunnel:latest"
        args = ["${NOMAD_TASK_DIR}/stunnel.conf"]
        ports = ["tls"]
      }

      resources {
        cpu = 100
        memory = 100
      }

      template {
        data = <<EOF
syslog = no
foreground = yes
delay = yes

[postgres_server]
accept = {{ env "NOMAD_PORT_tls" }}
connect = 127.0.0.1:5432
ciphers = PSK
PSKsecrets = {{ env "NOMAD_SECRETS_DIR" }}/stunnel_psk.txt
        EOF
        destination = "${NOMAD_TASK_DIR}/stunnel.conf"
      }

      template {
        data = <<EOF
{{ range nomadVarList "secrets/postgres/allowed_psks" -}}
{{ with nomadVar .Path }}{{ .psk }}{{ end }}
{{ end -}}
EOF
        destination = "${NOMAD_SECRETS_DIR}/stunnel_psk.txt"
      }
    }
  }
}