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

#------------------------------------------------------------------------------
# Version ID Block. Relies on +k filetype modifier.
# VersionID='$Id: //p4-sdp/main/Server/Unix/p4/common/bin/sync_replica.sh#1 $ $Change: 33433 $'

# 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))

TargetServerJournalPrefix=$(get_target_config_value journalPrefix)
if [[ -n "$TargetServerJournalPrefix" ]]; then
   CheckpointsDir="${TargetServerJournalPrefix%/*}"
else
   die "Could not determine journalPrefix of P4TARGET server of ServerID $SERVERID."
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.
if [[ -r "$P4ROOT/db.config" ]]; then
   export JDTmpDir=
   copy_jd_table "db.config" "$P4ROOT"
   TargetHost="$("$P4DBIN" -r "$JDTmpDir" -k db.config -jd - 2>/dev/null | grep "@${SERVERID}@ @P4TARGET@" | cut -d '@' -f 10)"
   remove_jd_tables
   if [[ "$TargetHost" == *:* ]]; then
      TargetHost=${TargetHost%:*}
      TargetHost=${TargetHost#*:}
   else
      die "Could not determine target host from $P4ROOT/db.config.  Tried:\\n$P4DBIN -r $P4ROOT -k db.config -jd - 2>/dev/null | grep @${SERVERID}@ @P4TARGET@ | cut -d '@' -f 10)"
   fi
else
   die "Expected file $P4ROOT/db.config is missing. Could not determine target host."
fi

# 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
   # shellcheck disable=SC2089
   RsyncCmd="rsync -av --exclude='.nfs*' --delete ${OSUSER}@${TargetHost}:$CheckpointsDir/ $CheckpointsDir"
   log "Executing: $RsyncCmd"
   eval "$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

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

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