#!/bin/bash

db=testdb

# default: use HEAD1 and HEAD2 instances (from unaltered git master instances)
port1=6511 project1=HEAD1
port2=6512 project2=HEAD2

if [[ "$1" == "6972" ]]
then
    # use the logical_replication and logical_replication2 instances (these aer instances of patched master).
    port1=6972 project1=logical_replication
    port2=6973 project2=logical_replication2
fi
# echo '\dRp' | psql -d $db -qX -p $port1
# echo '\dRs' | psql -d $db -qX -p $port2

if [[ $( pg_isready -qp $port1 -d $db ) -eq 0 ]]
then

echo "select  
      $port1 as \"$port1\"
    ,'pgst.repl' as pgstatrepl
    , substring(now()::text, 1, 22) as now
    , pid  
--  , usesysid 
--  , usename  
--  , application_name as appname
--  , client_addr 
--  , client_hostname 
--  , client_port 
    , substring(backend_start::text, 13, length('yyyy-mm-dd HH:MM:SS.ss')) as b_start
    , backend_xmin as b_xmin 
    , state   
    , sent_lsn  
    , write_lsn 
    , flush_lsn 
    , replay_lsn
    , write_lag 
    , flush_lag    
    , replay_lag 
--  , sync_priority 
--  , sync_state
from pg_stat_replication
-- where application_name = 'derail2' 
;

select 
    $port1 as \"$port1\"
  ,'pg_repl.slots' as pgreplslots
  , *
from pg_replication_slots  ;

\\c - - - $port2

select 
    $port2 as \"$port2\"
  , 'pg_subscr.' as  pgsubscr
  , *
from pg_subscription ;

select 
    $port2 as \"$port2\"
  , 'pg_subscr.rel' as pgsubscr_rel
  , *
from pg_subscription_rel ;  
" | psql -X -p $port1 -d $db | grep -Ev '^[(].+ row|^---|^You are now connected'
else
   echo "-- pg_isready -p $port1  -- not running"
fi


