#!/usr/bin/env bash
set -e

export SDP_ENV=/p4/common/bin/p4_vars
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

declare StatusMessage="OK: Cache purge OK."
declare Log=Unset
declare -i PurgeFailed=
declare -i ExitCode=0

function msg () { if [[ $Log != Unset ]]; then echo -e "$*" >> $Log; else echo -e "$*"; fi; }

function cmd ()
{
    tmpf=/tmp/t_cachepurge.$$
    msg "$*" >> $Log
    $* > $tmpf 2>&1
    status=$?
    cat $tmpf >>$Log
    rm -f $tmpf
    return $status
}

source $SDP_ENV $SDP_INSTANCE ||\
   bail "Failed to load SDP environment for instance $SDP_INSTANCE."

source $P4CBIN/backup_functions.sh ||\
   bail "Failed to load backup_functions.sh."

check_vars
set_vars
get_journalnum

[[ $Log == Unset ]] && Log=$LOGS/p4cachepurge.log

# This is needed because everything in backup_functions.sh uses LOGFILE including the mail_log_file function.
LOGFILE=$Log

rotate_log_file $LOGFILE ".gz"
remove_log_files "p4cachepurge.log" $KEEPLOGS

msg "${0##*/} Starting cache purge at $(date +'%a %Y-%m-%d %H:%M:%S %Z')."

P4="$P4BIN -p $P4PORT -u $P4USER"
$P4CBIN/p4login

PurgeFailed=0

# You need to modify this command to run on the depots you want to purge. You can duplicate the line for multiple paths.
cmd $P4 cachepurge -f 1000000000000 -R -O -D "//depot/release/..." || PurgeFailed=1


if [[ $PurgeFailed -ne 0 ]]; then
   StatusMessage="Error: Cache purge attempt failed.  Review the log [$Log]."
   mail_log_file "$HOSTNAME $P4SERVER P4 Cache Purge Log ($StatusMessage)"
   ExitCode=1
fi

msg "Completed cache purge at $(date)."
