#!/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/r26.1.0.BETA/Server/Unix/p4/common/bin/recreate_offline_db.sh#1 $ $Change: 33444 $'

# 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/INSTANCE/checkpoints directory is
# bad (i.e. 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.

declare SDPRoot="${SDP_ROOT:-/p4}"
declare SDPCommon="${SDPRoot}/common"
declare SDPCommonBin="${SDPCommon}/bin"
declare SDPCommonLib="${SDPCommon}/lib"
declare LogLink=
declare -i ErrorCount=0

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 "$SDPCommonBin/p4_vars" "$SDP_INSTANCE"
# shellcheck disable=SC1091
source "$SDPCommonBin/backup_functions.sh"

#==============================================================================
# SDP Library Functions

if [[ -d "$SDPCommonLib" ]]; then
   # shellcheck disable=SC1090 disable=SC1091
   source "$SDPCommonLib/logging.lib" ||\
      bail "Failed to load bash lib [$SDPCommonLib/logging.lib]. Aborting."
fi

#==============================================================================
# Local Functions

function msg () { echo -e "$*"; }
function errmsg () { msg "\\nError: ${1:-Unknown Error}\\n"; ErrorCount+=1; }
function bail () { errmsg "${1:-Unknown Error}"; exit "${2:-1}"; }

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

export LOGFILE
LOGFILE="$LOGS/recreate_offline_db.$(date +'%Y-%m-%d-%H%M%S').log"

# The LogLink symlink has no timestamp. It points to the most recent log file.
LogLink="$LOGS/recreate_offline_db.log"

if [[ -e "$LogLink" ]]; then
   if [[ -L "$LogLink" ]]; then
      rm -f "$LogLink"
   else
      # If the name that should be a symlink is not a symlink, move it aside before
      # creating the symlink.
      OldLogTimestamp=$(get_old_log_timestamp "$LogLink")
      mv -f "$LogLink" "${LogLink%.log}.${OldLogTimestamp}.log"
   fi
fi

# Point LogLink symlink to current log. Use a subshell so the 'cd' doesn't persist.
( cd "$LOGS" && ln -s "${LOGFILE##*/}" "${LogLink##*/}"; )

######### Start of Script ##########
check_vars
set_vars
check_uid
check_dirs
ckp_running
get_journalnum
# Drop the journal number by one since we are not truncating the journal and
# replay_journals_to_offline_db assumes a truncate_journal has been run.
JOURNALNUM=$((JOURNALNUM-1))
log "Start $P4SERVER recreate of offline db"
recreate_offline_db_files
log "Offline db basic recovery completed"
"$P4CBIN"/p4login
get_offline_journal_num
replay_journals_to_offline_db
log "End $P4SERVER recreate offline db"
mail_log_file "$HOSTNAME $P4SERVER recreate offline db log."
ckp_complete
