#!/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 recreates offline_db files from the latest checkpoint. If it fails, then
# check to see if the most recent checkpoint in the /p4/SDP_INSTANCE/checkpoints directory is
# bad (ie doesn't look like the right size compared to the others), and if so, delete it
# and rerun this script. If the error you are getting is that the journal replay failed,
# then the only option is to run live_checkpoint.sh script.
#
# 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.
#
#
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
# We put the date directly on this file because we don't call rotate_last_run_logs in this 
# script since it is normally a one off run script. The regular backup scripts will maintain
# the specified number of these logs per the $KEEPLOGS variable in p4_vars.
LOGFILE=$LOGS/recreate_offline_db.log.$(date +'%Y:%m:%d-%H:%M:%S')

######### Start of Script ##########
check_vars
set_vars
check_uid
check_dirs
ckp_running
get_journalnum
log "Start $P4SERVER recreate of offline db"
recreate_offline_db_files
log "Offline db basic recovery completed"
$P4CBIN/p4login
get_journalnum
get_offline_journal_num
replay_journals_to_offline_db
log "End $P4SERVER recreate offline db"
ckp_complete
