#!/bin/sh

ROOT=`pwd`
BINDIR=$ROOT/bin

PORT_PRIMARY=55432
PORT_SECONDARY=55433

# Const
N_TABLES=1000
N_TABLE_ROWS=100

# Create tables
CREATE_SQL=""

for i in `seq 1 $N_TABLES`
do
  CREATE_SQL="${CREATE_SQL} 
  create table if not exists t_$i as
    select g, md5(g::text)
    from generate_series(1, $N_TABLE_ROWS) g;\n"
done

echo $CREATE_SQL > create.sql.tmp
echo -n "Creating tables ... "
$BINDIR/psql -dpostgres -p$PORT_PRIMARY --quiet --tuples-only -fcreate.sql.tmp
rm -f create.sql.tmp
echo "DONE"

# Warm up the servers
WARMUP_SQL=""

for i in `seq 1 $N_TABLES`
do
  WARMUP_SQL="${WARMUP_SQL} 
  select pg_prewarm('t_$i');"
done

echo $WARMUP_SQL > warmup.sql.tmp
echo -n "Warm up tables ... "
$BINDIR/psql -dpostgres -p$PORT_PRIMARY   -q -fwarmup.sql.tmp > /dev/null
$BINDIR/psql -dpostgres -p$PORT_SECONDARY -q -fwarmup.sql.tmp > /dev/null
rm -f warmup.sql.tmp
echo "DONE"

# Watch for tables
$BINDIR/psql -dpostgres -p$PORT_PRIMARY --quiet --tuples-only -c"
call f_watch('PRIMARY', 3);
" &

$BINDIR/psql -dpostgres -p$PORT_SECONDARY --quiet --tuples-only -c"
call f_watch('SECONDARY', 6);
" &

# Delete tables
DELETE_SQL=""

for i in `seq 1 $N_TABLES`
do
  DELETE_SQL="${DELETE_SQL}
  drop table t_"$i";"
done

echo $DELETE_SQL > drop.sql.tmp
echo -n "Begin dropping tables ... "
$BINDIR/psql -dpostgres -p$PORT_PRIMARY --quiet --tuples-only -fdrop.sql.tmp
echo "DONE"
rm -f drop.sql.tmp

# Wait for jobs to be done
wait $(jobs -p)
