#!/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 

# shellcheck disable=SC1091
source /p4/common/bin/p4_vars "$SDP_INSTANCE"
# shellcheck disable=SC1091
source /p4/common/bin/backup_functions.sh
LOGFILE="$LOGS/sync_replica.log"

######### Start of Script ##########
check_vars
set_vars
rotate_last_run_logs
log "Starting sync_replica.sh"

if [[ "${P4REPLICA}" == "FALSE" ]]; then
  die "Error: sync_replica can only be run a read only or forwarding replica." 
fi

check_uid

"$P4CBIN/p4login" -p "$P4MASTERPORT"
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.

# shellcheck disable=SC2034
JOURNALNUM=$((MASTERJOURNALNUM-1))

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

   if [[ "$rsync_exit_code" -ne 0 ]]; then
      die "Error: Failed to pull $CHECKPOINTS from host $P4MASTERHOST.  The rsync exit code was: $rsync_exit_code.  Aborting."
   fi
else
   log "Skipping rsync of $CHECKPOINTS because SHAREDDATA is $SHAREDDATA."
fi

recreate_offline_db_files
get_offline_journal_num
replay_journals_to_offline_db
"$P4CBIN/p4login"
check_disk_space
remove_old_logs
remove_old_checkpoints_and_journals
log "End $P4SERVER sync replica"
mail_log_file "$HOSTNAME $P4SERVER Daily sync replica log."
