#!/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.sh can only run on a 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))

JournalPrefix="$("$P4DBIN" -r "$P4ROOT" -k db.config -jd - | grep "@${SERVERID}@ @journalPrefix@" | cut -d '@' -f 10)"
if [[ -n "$JournalPrefix" ]]; then
   CheckpointsDir="${JournalPrefix%/*}"
else
   log "Warning: Could not determine journalPrefix for ServerID $SERVERID."
   CheckpointsDir="${CHECKPOINTS}"
fi

# Determine the target host from P4TARGET, which is a P4PORT setting. Extract
# the server host from this value. The value extracted must be suitable with
# passwordless ssh for rsync usage.
TargetHost="$("$P4DBIN" -r "$P4ROOT" -k db.config -jd - | grep "@${SERVERID}@ @P4TARGET@" | cut -d '@' -f 10)"
TargetHost=${TargetHost%:*}
TargetHost=${TargetHost#*:}

# 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}@${TargetHost}:$CheckpointsDir/ $CheckpointsDir"
   log "Executing: $RsyncCmd"
   $RsyncCmd >> "$LOGFILE" 2>&1
   rsync_exit_code=$?

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

if [[ "$SHAREDDATA" == "FALSE" ]]; then
   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
else
   recreate_offline_db_files 1
   get_offline_journal_num
   replay_journals_to_offline_db 1
   "$P4CBIN/p4login"
   check_disk_space
   remove_old_logs
   remove_old_checkpoints_and_journals 1
fi

log "End $P4SERVER sync replica"
mail_log_file "$HOSTNAME $P4SERVER Daily sync replica log."
