#!/bin/bash
export SDP_INSTANCE=${SDP_INSTANCE:-Undefined}
export SDP_INSTANCE=${1:-$SDP_INSTANCE}
if [[ $SDP_INSTANCE == Undefined ]]; then
   echo "Instance parameter not supplied."
   echo "You must supply the Perforce instance as a parameter to this script."
   exit 1
fi

ERROR=0
ERRORTEXT=""

. /p4/common/bin/p4_vars $SDP_INSTANCE
. /p4/common/bin/backup_functions.sh

$P4CBIN/p4login

P4="$P4BIN -p ${P4PORT} -u $P4USER"

LOGFILE=$LOGS/replica_status.log

function get_replica_status ()
{
  $P4 -Ztag -v net.maxwait=30 pull -ljv 2>&1 | grep -v LEOF > $LOGFILE || die "Replica pull command failed. Abort!"

  if ( grep "Connection refused" $LOGFILE > /dev/null 2>&1 ); then
    ERRORTEXT="ERROR - The replica is offline!"
    ERROR=1
  fi

  if ( grep "\-1" $LOGFILE > /dev/null 2>&1 ); then
    ERRORTEXT="ERROR - The replica is out of sync!"
    ERROR=1
  fi

  if ( grep -i "password" $LOGFILE > /dev/null 2>&1 ); then
    ERRORTEXT="ERROR - The admin user is not logged in!"
    ERROR=1
  fi

  if ( grep -i "Replica access to P4TARGET server failed." $LOGFILE > /dev/null 2>&1 ); then
    ERRORTEXT="ERROR - Replica access to P4TARGET server failed."
    ERROR=1
  fi

  if [[ $ERROR -eq 0 ]];then
    REPLICAJOURNAL=$(grep "replicaJournalCounter " $LOGFILE | cut -d " " -f 3)
    MASTERJOURNAL=$(grep "masterJournalNumber " $LOGFILE | cut -d " " -f 3)
    CURRENTJOURNAL=$(grep "currentJournalNumber " $LOGFILE | cut -d " " -f 3)
    if [[ $CURRENTJOURNAL ]]; then
      MASTERJOURNAL=$CURRENTJOURNAL
    fi
  fi
}

######### Start of Script ##########
get_replica_status

if [[ $ERROR -eq 0 ]];then
  if [[ $REPLICAJOURNAL -ne $MASTERJOURNAL ]];then
    sleep 900
    get_replica_status
    if [[ $REPLICAJOURNAL -ne $MASTERJOURNAL ]];then
      ERRORTEXT="ERROR - The replica is out of sync!"
      ERROR=1
    fi
  fi
fi

if [[ $ERROR -eq 0 ]]; then
  if [ ! ls $LOGS/replica_status_notified* > /dev/null 2>&1 ]; then
    mail_log_file "$HOSTNAME $P4SERVER Replica Status back to normal."
  fi
  rm -f $LOGS/replica_status_notified* > /dev/null 2>&1
fi

if [[ $ERROR -eq 1 ]];then
  if [ ! -f $LOGS/replica_status_notified.$(date +%d) ];then
    mail_log_file "$ERRORTEXT $HOSTNAME $P4SERVER Replica Status."
    touch $LOGS/replica_status_notified.$(date +%d)
  fi
fi
