#!/bin/bash
set -u

# Version ID Block. Relies on +k filetype modifier.
#------------------------------------------------------------------------------
# shellcheck disable=SC2016
declare VersionID='$Id: //p4-sdp/dev_c2s/Server/Unix/p4/common/bin/opt_perforce_sdp_backup.sh#3 $ $Change: 31580 $'
declare VersionStream=${VersionID#*//}; VersionStream=${VersionStream#*/}; VersionStream=${VersionStream%%/*};
declare VersionCL=${VersionID##*: }; VersionCL=${VersionCL%% *}
declare Version=${VersionStream}.${VersionCL}
[[ "$VersionStream" == r* ]] || Version="${Version^^}"

declare ThisScript="${0##*/}"
declare ThisUser=
declare ThisHost=${HOSTNAME%%.*}
declare PerforcePackageBase=/opt/perforce
declare SDPPackageBase="$PerforcePackageBase/helix-sdp"
declare BackupBase="/hxdepots/backup"
declare BackupDir="$BackupBase/opt_perforce_helix-sdp.$ThisHost"
declare RsyncCmd=
declare -i Debug=${SDP_DEBUG:-0}
declare -i ErrorCount=0

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

function msg () { echo -e "$*"; }
function dbg () { [[ "$Debug" -eq 0 ]] || msg "DEBUG: $*"; }
function errmsg () { msg "\\nError: ${1:-Unknown Error}\\n"; ErrorCount+=1; }
function bail () { errmsg "${1:-Unknown Error}"; exit "${2:-1}"; }

ThisUser=$(id -n -u)
msg "Started $ThisScript version $Version as $ThisUser@$ThisHost on $(date)."

dbg "Starting Preflight Checks."

if [[ "$ThisUser" == root ]]; then
   dbg "Verified: Running as root"
else
   errmsg "Run this as root, not $ThisUser."
fi

if [[ -d "$SDPPackageBase" ]]; then
   dbg "Verified: $SDPPackageBase directory exists."
else
   errmsg "SDP OS Package Structure [$SDPPackageBase] does not exists. Use this script only if that structure exists."
fi

mkdir -p "$BackupBase" ||\
   errmsg "Could not do: mkdir -p \"$BackupBase\""

if [[ -d "$BackupBase" && -w "$BackupBase" ]]; then
   dbg "Verified: $BackupBase directory exists and is writable."
else
   errmsg "The BackupBase directory [$BackupBase] does not exist or is not writable."
fi

if [[ "$ErrorCount" -eq 0 ]]; then
   dbg "Preflight checks OK."
else
   bail "Aborting due to failed preflight checks."
fi

RsyncCmd="rsync -av $SDPPackageBase/ $BackupDir"
if eval "$RsyncCmd"; then
   msg "SDP Package Backup to $BackupDir was successful."
else
   bail "SDP Package Backup to $BackupDir failed."
fi

exit "$ErrorCount"
