#!/bin/sh

ROOT=`pwd`
BINDIR=$ROOT/bin

DATADIR="$ROOT/data"
DATA_PRIMARY=$DATADIR/primary
DATA_SECONDARY=$DATADIR/secondary

LOGSDIR="$DATADIR/logs"
LOGS_PREFIX=`date +"%F_%T"`
LOG_PRIMARY=$LOGSDIR/$LOGS_PREFIX.primary.log
LOG_SECONDARY=$LOGSDIR/$LOGS_PREFIX.secondary.log

PORT_PRIMARY=55432
PORT_SECONDARY=55433
SHBUF_PRIMARY_SIZE="10 GB"
SHBUF_SECONDARY_SIZE="20 GB"

# Run the servers
$BINDIR/pg_ctl -D$DATA_PRIMARY   -l"$LOG_PRIMARY" \
	-o"--port=$PORT_PRIMARY   --shared_buffers='$SHBUF_PRIMARY_SIZE'" start
$BINDIR/pg_ctl -D$DATA_SECONDARY -l"$LOG_SECONDARY" \
	-o"--port=$PORT_SECONDARY --shared_buffers='$SHBUF_SECONDARY_SIZE'" start

# Const
PG_CODE='$$'

# Create procedures
$BINDIR/psql -dpostgres -p$PORT_PRIMARY <<EOF
---
--- Procedure f_watch: watch for moments of deleting/adding any tables in
--- public scheme, except for the the t_filler.
---
--- This procedure watch for the two moments:
--- 1. When the number of tables has changed for the first time (since run).
--- 2. When the number of tables becomes equal to zero.
---
--- The output is provided by "rise info".
---
create or replace procedure f_watch(node text, notice_delay int = 5)
language plpgsql
as
$PG_CODE
declare
  n bigint;
  i bigint;
  start timestamptz;
  finish timestamptz;
  s text;
begin
  select count(*) into n
  from pg_tables 
  where schemaname = 'public' and tablename <> 't_filler';

  loop
    select count(*) into i
    from pg_tables
    where schemaname = 'public' and tablename <> 't_filler';

    if i <> n then
      start := clock_timestamp();
      exit;
    end if;
  end loop;

  loop
    select count(*) into i
    from pg_tables
    where schemaname = 'public' and tablename <> 't_filler';

    if i = 0 then
      finish := clock_timestamp();
      exit;
    end if;

    perform pg_sleep(1);
  end loop;

  perform pg_sleep(notice_delay);

  select replace(replace(format('%-48s', node||'*'), ' ', '-'), '*', ' ') 
  into s;

  raise info ' % ', s;
  raise info '  Start delete at : %', start;
  raise info ' Finish delete at : %', finish;
  raise info '          It took : %', (finish - start);

  select repeat('-', 48)
  into s;
  raise info ' % ', s;
end $PG_CODE ;
EOF

echo " *** STEP 1 *** "
./run-001-core.sh
echo " *** STEP 2 *** "
./run-001-core.sh
echo " *** STEP 3 *** "
./run-001-core.sh
echo " *** STEP 4 *** "
./run-001-core.sh
echo " *** STEP 5 *** "
./run-001-core.sh

# Stop the servers
$BINDIR/pg_ctl -D$DATA_PRIMARY stop
$BINDIR/pg_ctl -D$DATA_SECONDARY stop
