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

# This script is using the following external variables:
#
# SDP_INSTANCE - The instance of Perforce that is being backed up. If not
# set in environment, pass in as argument to script.
#
# P4HOME - Server's home directory.
# P4BIN - Command line client name for the instance being backed up.
# P4DBIN - Server executable name for the instance being backed up.
# P4ROOT - Server's root directory. p4/root, p4_N/root
# P4PORT - TCP/IP port for the server instance being backed up.
# P4JOURNAL - Location of the Journal for the server instance being backed up.
#

declare -i RebuildOfflineDB=1

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 

# The '-skip_odb' option is currently an undocumented feature, though it will be
# documented in a future release (pending a separate change to normalize command
# line processing to add '-h' and '-man' options across all key scripts).  If
# '-skip_odb' is specified, the live checkpoint of files in P4ROOT is created
# per usual, but the replay of the newly generated checkpoint to the offline_db
# is skipped.  If this option is used, instructions are provided to use the
# recreate_offline_db.sh script to do the rebuild later.
[[ "${2:-}" == "-skip_odb" ]] && RebuildOfflineDB=0

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

######### Start of Script ##########
check_vars
set_vars
rotate_last_run_logs
log "Start $P4SERVER Checkpoint"
check_uid
check_dirs
ckp_running
"$P4CBIN"/p4login
get_journalnum
checkpoint
if [[ "$RebuildOfflineDB" -eq 1 ]]; then
   recreate_offline_db_files
else
   log "Skipping rebuild of offline_db due to '-skip_odb'."
fi
remove_old_checkpoints_and_journals
remove_old_logs
set_counter

[[ "$RebuildOfflineDB" -eq 0 ]] && \
   log "The offline_db was not rebuilt due do '-skip_odb'. Rebuild later with:\\n\\tnohup recreate_offline_db.sh ${SDP_INSTANCE} < /dev/null > /dev/null 2>&1 &\\n\\ttail -f $LOGS/recreate_offline_db.log\\n\\n"

log "End $P4SERVER Checkpoint"

mail_log_file "$HOSTNAME $P4SERVER live checkpoint log."
ckp_complete
