#!/bin/bash
#==============================================================================
# Copyright and license info is available in the LICENSE file included with
# the Server Deployment Package (SDP), and also available online:
# https://swarm.workshop.perforce.com/projects/perforce-software-sdp/view/main/LICENSE
#------------------------------------------------------------------------------

# Intended to be run on a replica machine to sync replica from its corresponding master
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 

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

######### Start of Script ##########
check_vars
set_vars

LOGFILE=$LOGS/sync_replica.log

check_uid

$P4BIN -u $P4USER -p ${P4MASTERPORT} login < /p4/common/config/.p4passwd.${P4SERVER}.admin > /dev/null 2>&1
MASTERJOURNALNUM=$($P4BIN -u $P4USER -p ${P4MASTERPORT} counter journal)

if [[ "$MASTERJOURNALNUM" == "" ]]; then
   die "Error:  Couldn't get journal number from master.  Aborting."
fi

# We set JOURNALNUM to one less than the master since we are not truncating the journal
# and replay_journals_to_offline_db assumes that truncate_journal has been run.

JOURNALNUM=$(($MASTERJOURNALNUM-1))

rotate_last_run_logs
log "Starting sync_replica.sh"

# You must set up a public keypair using "ssh-keygen -t rsa" in order for this to work.
# You need to paste your CLIENT ~/.ssh/id_rsa.pub contents into the REMOTE ~/ssh/authorized_keys file. 
if [[ "$SHAREDDATA" == "FALSE" ]]; then
  rsync -avz --delete ${OSUSER}@${P4MASTER}:$CHECKPOINTS/ $CHECKPOINTS > $LOGFILE 2>&1
  rsync_exit_code=$?

  if [[ $rsync_exit_code -ne 0 ]]; then
    die "Error: Failed to pull $CHECKPOINTS from host $P4MASTER.  The rsync exit code was: $rsync_exit_code.  Aborting."
  fi
fi

recreate_offline_db_files
get_offline_journal_num
replay_journals_to_offline_db

$P4BIN login < /p4/common/config/.p4passwd.${P4SERVER}.admin > /dev/null 2>&1

check_disk_space
remove_old_logs
export CHECKPOINTS=${P4HOME}/checkpoints.rep
remove_old_checkpoints_and_journals
log "End $P4SERVER sync replica"
mail_log_file "$HOSTNAME $P4SERVER Daily sync replica log."
