#!/bin/bash
################################################################################
# Copyright (c) 2013-2016 VMware, Inc. All rights reserved.
################################################################################
# Show replication status

ENCODING=UTF8
THIS_DIR=`dirname $0`

if [ -z $VMWARE_POSTGRES_BASE ]; then
   echo "VMWARE_POSTGRES_BASE is not set."
   echo "Check your installation."
   exit 1
fi
SANITY_FILE=$VMWARE_POSTGRES_BASE/scripts/vpostgres_sanity_checks
if [ -f $SANITY_FILE ]; then
   source $SANITY_FILE
else
   echo "Sanity check file for environment variables of VMware Postgres"
   echo "is not available. Check your installation."
   exit 1
fi

# Launch command
if [ -f $VMWARE_POSTGRES_DATA/recovery.conf ]; then
   # Try slave command
   $VMWARE_POSTGRES_BIN/psql -P pager=off -c \
   'with xl as (
      select pg_last_xlog_receive_location() as log_receive_position,
             pg_last_xlog_replay_location() as log_replay_position)
    select xl.log_receive_position as log_receive_position,
        xl.log_replay_position  as log_replay_position,
        pg_xlog_location_diff(xl.log_receive_position,
                              xl.log_replay_position) as replay_delta
    from xl;'
else
   # Command for master
   $VMWARE_POSTGRES_BIN/psql -P pager=off -c \
   'select sync_priority,
        application_name as slave,
        sync_state,
        flush_location as log_receive_position,
        replay_location as log_replay_position,
        pg_xlog_location_diff(sent_location, flush_location) as receive_delta,
        pg_xlog_location_diff(flush_location, replay_location) as replay_delta
    from pg_stat_replication
    order by sync_priority;'
fi
