#!/bin/bash
# usage: run_cases.sh <install prefix> <port> <sql file>
# Starts a throwaway cluster, sets up a postgres_fdw loopback server and
# runs the given SQL file.  Survives backend crashes: reports them.
P=$1; PORT=$2; SQL=$3
D=/tmp/fdwcases_$PORT
rm -rf $D
$P/bin/initdb -D $D -U postgres >/dev/null 2>&1
$P/bin/pg_ctl -D $D -o "-p $PORT -k /tmp" -l $D/log -w start >/dev/null
trap '$P/bin/pg_ctl -D $D -m immediate -w stop >/dev/null 2>&1; rm -rf $D' EXIT
$P/bin/psql -h /tmp -p $PORT -U postgres -X -q postgres <<SQL
CREATE EXTENSION postgres_fdw;
CREATE SERVER loopback FOREIGN DATA WRAPPER postgres_fdw
  OPTIONS (dbname 'postgres', port '$PORT', host '/tmp');
CREATE USER MAPPING FOR CURRENT_USER SERVER loopback OPTIONS (user 'postgres');
SQL
$P/bin/psql -h /tmp -p $PORT -U postgres -X -q -e postgres -f "$SQL" 2>&1
sleep 1
grep -E 'TRAP|terminated by signal' $D/log | sed 's/^/[server log] /'
