#!/usr/bin/env bash
set -euo pipefail

ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
env_file=${1:-"$ROOT/.env"}

"$ROOT/scripts/compose.sh" "$env_file" run --rm --no-deps migrate \
  /app/bin/who_need_help eval '
    Application.ensure_all_started(:ecto_sql)
    {:ok, _pid} = WhoNeedHelp.Repo.start_link()

    {:ok, %{rows: [[server, postgis, ssl]]}} =
      Ecto.Adapters.SQL.query(
        WhoNeedHelp.Repo,
        """
        SELECT
          version(),
          PostGIS_Version(),
          COALESCE(
            (SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()),
            false
          )
        """,
        []
      )

    IO.puts("Database check passed: PostgreSQL #{server}; PostGIS #{postgis}; TLS=#{ssl}")
  '
