Title: easyrsync.sh.2017.07.23
Created: 2018-04-29 22:09:52 +0000

#!/usr/local/Cellar/bash/4.4.12/bin/bash
#
# easyrsync.sh
#
# Description: An updated backup system written by Eric Swanson using rsync. Source and
#              destination paths are loaded from a file, src-dest.txt.
#
# 2017-07-08 Created outline in easyrsync.sh script
# 2017-07-09 First running version
# 2017-09-05 Added more info to display, improved error handling
# 2018-01-29 Added information to the log file
# 2018-02-23 Added source and destination paths to the top info line
#
# IMPORTANT: this is how to get it to work with filenames with spaces, set IFS to tab
#            (see example below) and double quote the filenames using backslash-doublequote
#echo about to ls -l \"${SRC_ARRAY[i]}\"
#eval ls -l \"${SRC_ARRAY[i]}\"
#echo
#echo about to ls -l \"${DEST_ARRAY[i]}\"
#eval ls -l \"${DEST_ARRAY[i]}\"
#echo

#
# General Program Setup
#

# debugging: echo commands after executing them
#set -x

# debugging: create error if we use a variable that is unset
set -u

# trap (allow) for control-c: switch back to primary screen, type a message and exit
trap 'tput rmcup; echo "User cancelled easyrsync with control-c."; exit 2' 2

# trap other early exits: switch back to primary tty screen, type a message
trap 'tput rmcup; echo "Exiting easyrsync."' 1 15

# variables
RSYNC_PATH=/usr/local/bin/rsync
SRC_DEST_FILE=/Volumes/Mg-Projects/Homes/ericswanson/Shell_Scripts/easyrsync/src-dest.txt
ARCHIVE_PATH="placeholder"
ARCHIVE_SIZE=0
ARCHIVE_RENAME="placeholder"
ERROR_LOG="placeholder"
LOG_FILE="placeholder"
BACKUP_ERRORS="placeholder"
# for some reason, can't send to eric_swanson@gial.edu
EMAIL="eric@ericjulie.com"

TABLE_HEAD="`tput sgr0`| `tput rev`###`tput sgr0` | `tput rev`Backup Name                                          `tput sgr0` | `tput rev` Source Size`tput sgr0` | `tput rev`   Dest Size`tput sgr0` | `tput rev`   Dest Free`tput sgr0` | `tput rev` Last Backup`tput sgr0` | `tput rev`Warnings                      `tput sgr0` |"
TABLE_LINE="+-----+-------------------------------------------------------+--------------+--------------+--------------+--------------+--------------------------------+"
declare -i TERM_COL=1
declare -i TERM_ROW=1

# i will hold the number of array items found
declare -i I=1

# d will LOOP 1 to i to display array items
declare -i D=1
LINE_NUMBER="000"
LINE_NAME="placeholder"
declare -i LOOP=1
DEST_FREE="0"
OK="n"
AREYOUSURE="n"
MODE="b"
MODE_TEXT="backup"
SWAPPATH="placeholder"
RSYNC_ERROR="n"
RSYNC_ANY_ERRORs="n"
SRC_INFO="OFFLINE"
declare -i SRC_SIZE=0
DEST_INFO="OFFLINE"
declare -i DEST_SIZE=0
declare -i DEST_FREE_SIZE=0
declare -i DEST_CHECK=0
LAST_BACKUP="placeholder"
NONE="        None"
declare -i SET_NUMBER=1
declare -i RSYNC_START=1
declare -i RSYNC_END=1
declare -i RSYNC_RUNNING=1

# IFS sets the inter frame separator to tab instead of space
# so filenames with spaces will work in the src-dest.txt file
IFS=$'\t'

declare -a BACKUP_SETS
declare -a BACKUP_NAME
declare -a SRC_ARRAY
declare -a DEST_ARRAY
declare -a RSYNC_SW_ARRAY

#
# FUNCTIONS
#

function pos
{
    local CURPOS
    read -sdR -p $'\E[6n' CURPOS
    CURPOS=${CURPOS#*[} # Strip decoration characters <ESC>[
    echo "${CURPOS}"    # Return position in "row;col" format
}
function row
{
    local COL
    local ROW
    IFS=';' read -sdR -p $'\E[6n' ROW COL
    echo "${ROW#*[}"
}
function col
{
    local COL
    local ROW
    IFS=';' read -sdR -p $'\E[6n' ROW COL
    echo "${COL}"
}

## in case the terminal was left in the alternate screen from a previous crash,
## we will now set the terminal to the primary screen
## this seems to bakup several lines:     tput rmcup

# erase from cursor to end of screen in case there is junk there
printf "\033[0J"

# put splash on original terminal screen before we switch to the alternate one
echo
tput rev
echo "   easyrsync   "
echo
tput sgr0

# make sure we are running as root/sudo
if [[ `id -u` -ne 0 ]] ; then echo "Please run as `tput smul`root`tput rmul`" ; echo ; exit 1 ; fi

# switch to alternate tty screen, clear screen, set text to normal
tput smcup
clear
tput sgr0

# find screen width
((TERM_COL=$(tput cols)/2))
TERM_COL=($TERM_COL-7)
((TERM_ROW=$(tput lines)/2))
TERM_ROW=$TERM_ROW-6
tput cup $TERM_ROW $TERM_COL
tput rev
echo "   EASYRSYNC   "
tput sgr0
((TERM_COL=$(tput cols)/2))
TERM_COL=($TERM_COL-17)
((TERM_ROW=$(tput lines)/2))
TERM_ROW=$TERM_ROW-4
tput cup $TERM_ROW $TERM_COL
echo "Easy backup and restore using rsync"
TERM_ROW=$TERM_ROW+4
TERM_COL=$TERM_COL+5
tput cup $TERM_ROW $TERM_COL
echo -n "Press Enter to Continue"
TERM_ROW=$TERM_ROW+1
TERM_COL=$TERM_COL-10
tput cup $TERM_ROW $TERM_COL
echo -n "Type Control-C to exit Easyrsync at any time"

# user input
read OK

#
# Main easyrsync screen gets drawn here
#
tput home
clear

# turn on scrolling region
printf "\033[8;`tput lines`r"

tput rev
echo "   easyrsync   "
tput sgr0
echo
echo
echo
echo

# draw a line across bottom of menu lines at top of screen
TERM_COL=$(tput cols)
LOOP=1

while [ $LOOP -le $TERM_COL ]; do
    echo -n "_"
    ((LOOP++))
    done
# put cursor below menu lines
tput cup 7 0

#
# Choose MODE, backup or restore
#

OK="n"

while

    [ $OK != "y" ]

do

    echo
    # now clear to end of line to erase any bad answers previously entered
    tput el

    echo -n "Choose MODE: `tput smul`Backup`tput rmul` [`tput rev`b`tput sgr0`] or `tput smul`Restore`tput rmul` [`tput rev`r`tput sgr0`]:  "

    # user input
    read MODE

    echo

    case "$MODE" in
    'b')
        # normal backup mode
        MODE_TEXT="backup"
        echo "Normal backup mode selected"
        # menu line
        # save cursor position
        tput sc
        # go to 2nd line, 20 characters in
        tput cup 1 20
        echo -n "Mode: `tput smul`Backup`tput rmul` "
        # restore cursor position
        tput rc

        OK="y"
        ;;

    'r')
        # restore mode
        MODE_TEXT="RESTORE"
        echo "`tput rev`RESTORE MODE SELECTED (DATA IS COPIED BACK)`tput sgr0`"
        echo "NOTE: Restore MODE will swap the source and destination paths."
        #echo "and then restore one directory up (i.e. cd ..) from stated path."
        echo "Restore will also save any existing data in an archive folder."
        # menu line
        # save cursor position
        tput sc
        # go to 2nd line, 20 characters in
        tput cup 1 20
        echo -n "Mode: `tput rev`Restore`tput sgr0`"
        # restore cursor position
        tput rc

        OK="y"
        ;;

     *)
        # invalid input
        tput blink
        echo -n "Invalid MODE choice:  $MODE"
        tput sgr0
        # read current cursor position
        TERM_ROW=$(row)
        # move cursor up to overwrite same line
        ((TERM_ROW=$TERM_ROW - 4))
        tput cup $TERM_ROW 0

        OK="n"
        ;;
    esac

done

#
# Choose Which Backup/Restore Set
#

# Find all backup sets
BACKUP_SETS=(/Volumes/Mg-Projects/Homes/ericswanson/Shell_Scripts/easyrsync/BACKUP_SETS/*.txt)

OK="n"

while

    [ $OK != "y" ]

do

    # Display all backup sets
    echo
    echo "Available Backup Sets"
    echo "====================="

    # Display available sets
    for ((I=0; I<${#BACKUP_SETS[@]}; I++)); do
        ((SET_NUMBER=$I + 1))
        tput rev
        # format the backup sets number to 2 digits (with leading zeros)
        LINE_NUMBER=`echo $SET_NUMBER | awk '{ printf( "%02d", $1) }'`
        echo -n "$LINE_NUMBER"
        tput sgr0
        echo " ${BACKUP_SETS[$I]##*/}"
    done
    echo
    echo -n "Choose $MODE_TEXT set:  "
    # now clear to end of line to erase any bad answers previously entered
    tput el

    # user input
    read SET_NUMBER

    # SET_NUMBER must be from 1 to I
    if (("SET_NUMBER">=1 && "SET_NUMBER"<=$I))
    then
        # Valid input
        # clear to end of line in case previous error text
        tput el
        OK="y"
    else
        # Invalid input
        echo
        tput blink
        echo -n "Invalid SET choice:  $SET_NUMBER"
        tput el
        tput sgr0
        #read current cursor position
        TERM_ROW=$(row)
        # move cursor up to overwrite same line
        ((TERM_ROW=$TERM_ROW - ($I+7)))
        tput cup $TERM_ROW 0
        OK="n"
    fi
done

# we have valid input now

# decrement set number to get true number
((SET_NUMBER--))
SRC_DEST_FILE=${BACKUP_SETS[$SET_NUMBER]}
echo

# menu line
# save cursor position
tput sc
# go to 2nd line, 40 characters in
tput cup 1 40
echo -n "Backup Set:        `tput smul`${SRC_DEST_FILE##*/}`tput rmul`"
# restore cursor position
tput rc

#
# User chooses which backup set to use
#

#
# Read array from src-dest.txt file, ignoring blank lines and comment lines
# starting with #.
# Array definition: (/source path/)(tab)(/destination path/)(tab)(-rsync switches)
#

# Open file descriptor 3 for reading the array file
exec 3<> $SRC_DEST_FILE

# While LOOP to read all lines from the file
I=1

while

   read -u 3 BACKUP_NAME[I] SRC_ARRAY[I] DEST_ARRAY[I] RSYNC_SW_ARRAY[I]

do

    # test for blank entries in source or destination or non-root file paths
    # and discard this read if found
    if [ -z ${SRC_ARRAY[I]} ] || \
        [ -z ${DEST_ARRAY[I]} ] || \
        [ ${SRC_ARRAY[I]:0:1} != "/" ] || \
        [ ${DEST_ARRAY[I]:0:1} != "/" ] || \
        [ ${RSYNC_SW_ARRAY[I]:0:1} != "-" ] || \
        [ ${BACKUP_NAME[I]:0:1} = "#" ]
    then
        # clearing this entry in case it is the last one
        unset BACKUP_NAME[I]
        unset SRC_ARRAY[I]
        unset DEST_ARRAY[I]
        unset RSYNC_SW_ARRAY[I]
    else
        # increment i counter
        ((I++))
    fi
done

# variable {I} will always be one too many at the end of LOOP
((I--))

# Close the array file
exec 3>&-

#
# Display array and other useful information
#

echo "$TABLE_LINE"
echo "$TABLE_HEAD"
echo "$TABLE_LINE"

while

    ((D<=I))

do

    # format the backup number to 3 digits
    LINE_NUMBER=`echo $D | awk '{ printf( "%03d", $1) }'`
    echo -n "| `tput rev`$LINE_NUMBER`tput sgr0` | "

    # format the backup name
    LINE_NAME=`echo ${BACKUP_NAME[D]::53} | awk '{ printf"%-53s", $0 }'`
    echo -n "$LINE_NAME | "

    # let's see if the src path is a directory (and is online)
    if [ -d "${SRC_ARRAY[D]}" ]
    then
        # yes the source is a directory that can be found right now
        # save cursor position, display calculating message
        tput sc
        echo -n " Calculating |"
        tput rc

        # find the size
        SRC_INFO=`du -sh "${SRC_ARRAY[D]}" 2>/dev/null | awk '{ printf "%12s", $1 }'`
        SRC_SIZE=`du -s "${SRC_ARRAY[D]}" 2>/dev/null | awk '{ printf "%12s", $1 }'`
    else
        # no, the source is not a directory or offline
        SRC_INFO=" --OFFLINE--"
        SRC_SIZE=0
    fi
    echo -n "$SRC_INFO | "

    # let's see if the dest path is a directory (and is online)
    if [ -d "${DEST_ARRAY[D]}" ]
    then
        # yes the source is a directory that can be found right now
        # save cursor position, display "calculating" message
        tput sc
        echo -n " Calculating |"
        tput rc

        # find the size
        DEST_INFO=`du -sh "${DEST_ARRAY[D]}" 2>/dev/null | awk '{ printf "%12s", $1 }'`
        DEST_SIZE=`du -s "${DEST_ARRAY[D]}" 2>/dev/null | awk '{ printf "%12s", $1 }'`
    else
        # no, the source is not a directory or offline
        DEST_INFO=" --OFFLINE--"
        DEST_SIZE=0
    fi
    echo -n "$DEST_INFO | "

    # display free space at destination
    # save cursor position, display calculating message
    tput sc
    echo -n " Calculating |"
    tput rc

    DEST_FREE=`df -h "${DEST_ARRAY[D]}" 2>/dev/null | tail -1 | awk '{ printf "%12s", $4 }'`
    DEST_FREE_SIZE=`df "${DEST_ARRAY[D]}" 2>/dev/null | tail -1 | awk '{ printf "%12s", $4 }'`

    # check if error (destination folder not created yet) if so, print spaces
    if [ -z "$DEST_FREE" ]
    then
        DEST_FREE="            "
        DEST_FREE_SIZE=0
    fi
    echo -n "$DEST_FREE |"

    # display last backup date
        tput sc
    echo -n " Calculating |"
    tput rc

    if [ -e "${DEST_ARRAY[D]}.latest-rsync-date" ]
    then
        # Month
        LAST_BACKUP=`ls -l "${DEST_ARRAY[D]}.latest-rsync-date" | awk '{print $6}'`
        # Format the day as two digits
        LAST_BACKUP=$LAST_BACKUP" "`ls -l "${DEST_ARRAY[D]}.latest-rsync-date" | awk '{printf "%2s", $7'}`
        # The rest of the date
        LAST_BACKUP=$LAST_BACKUP" "`ls -l "${DEST_ARRAY[D]}.latest-rsync-date" | awk '{print $8}'`
    else
        LAST_BACKUP=$NONE
        #LAST_BACKUP=""
    fi
    echo -n " $LAST_BACKUP |"

    # check if enough disk space at destination calculated roughly as: if (source size) > (dest size) + (dest free space)
    DEST_CHECK=$DEST_SIZE+$DEST_FREE_SIZE
    if [ $SRC_SIZE -gt $DEST_CHECK ]
    then
        # source size is larger than destination (probably not enough space on destination HDD)
        echo " `tput rev`** CHECK SPACE AVAILABILITY **`tput sgr0` |"
    else
        # destination is larger or equal to the source size (destination HDD has enough space to backup to)
        echo "                                |"
    fi


    # increment d counter
    ((D++))

done

# table bottom line
echo "$TABLE_LINE"

#
# User chooses first and last backup in array to run
#
while

    [ $AREYOUSURE != "y" ]

do

    # choose first backup in array to start at
    OK="n"

    # CLEAR MENU LINE OF FIRST AND LAST BACKUP INCASE NOT FIRST TIME THROUGH
    # menu line
    # save cursor position
    tput sc
    # go to 3rd line, 0 characters in
    tput cup 2 0
    # erase to end of line
    tput el
    # restore cursor position
    tput rc


    while

        [ $OK != "y" ]

     do

        #
        # choose first backup in array to run
        #

        echo
        echo -n "Choose which `tput smul`$MODE_TEXT to start at`tput rmul` from list above:  "
        # clear to end of line in case previous error entries present
        tput el

        # user input
        read RSYNC_START

        echo

        # check input, not zero, <= table items
        if [ -z $RSYNC_START ] || [ $RSYNC_START -lt 1 ] || [ $RSYNC_START -gt $I ]
        then
            # invalid input
            tput blink
            echo -n "$RSYNC_START is an invalid start number"
            # erase to end of line in case previous error
            tput el
            tput sgr0
            # read current cursor position
            TERM_ROW=$(row)
            # move cursor up to overwrite same line
            ((TERM_ROW=$TERM_ROW - 4))
            tput cup $TERM_ROW 0

            OK="n"
        else
            # valid input
            echo "Starting at $MODE_TEXT number:  $RSYNC_START  ${MODE_TEXT^} name:  `tput rev`${BACKUP_NAME[$RSYNC_START]}`tput sgr0`"
            OK="y"

            # menu line
            # save cursor position
            tput sc
            # go to 3rd line, 40 characters in
            tput cup 2 40
            echo -n "Starting Number:   `tput smul`$RSYNC_START`tput rmul`"
            # restore cursor position
            tput rc

        fi

    done

    #
    # choose last backup in array to run
    #

    OK="n"

    # if start is the last one in the array, then end will also be the last one
    if [ $RSYNC_START -eq $I ]
    then
        RSYNC_END=$RSYNC_START
        # skip asking for end number in this case
        OK="y"
    fi

    while

        [ $OK != "y" ]

    do

        echo
        echo -n "Choose which `tput smul`$MODE_TEXT to end at`tput rmul` from list above:    "
        # clear to EOL to erase previous error input if any
        tput el
        read RSYNC_END
        echo

        # check input, not zero, < start number, not > table item count
        if [ -z $RSYNC_END ] || [ $RSYNC_END -lt $RSYNC_START ] || [ $RSYNC_END -gt $I ]
        then
            # invalid input
            tput blink
            echo -n "$RSYNC_END is an invalid ending number"
            tput el
            tput sgr0
            # read current cursor position
            TERM_ROW=$(row)
            # move cursor up to overwrite same line
            ((TERM_ROW=$TERM_ROW - 4))
            tput cup $TERM_ROW 0

            OK="n"
        else
            # valid input
            OK="y"
        fi

    done

    echo "Ending at $MODE_TEXT number:    $RSYNC_END  ${MODE_TEXT^} name:  `tput rev`${BACKUP_NAME[$RSYNC_END]}`tput sgr0`"

    # menu line
    # save cursor position
    tput sc
    # go to 3rd line, 65 characters in
    tput cup 2 65
    echo -n "Ending Number:  `tput smul`$RSYNC_END`tput rmul`"
    # restore cursor position
    tput rc


    echo
    echo -n "Are these settings correct [`tput rev`y`tput sgr0`] or [`tput rev`n`tput sgr0`]:  "

    # user input
    read AREYOUSURE

    echo

# AREYOUSURE LOOP
done

#
# Loop through all backups, running them
#
RSYNC_RUNNING=RSYNC_START

# set error log file name
BACKUP_ERRORS="/tmp/easyrsync-temp-`date "+%Y-%m-%d-%H.%M.%S$$"`".log

# does the error log file already exist?
if [[ -f $BACKUP_ERRORS ]]
then
    # delete the file if it already exists
    rm $BACKUP_ERRORS
fi

# create blank error file
touch $BACKUP_ERRORS

#
# MAIN RSYNC LOOP
#

while

    [ $RSYNC_RUNNING -le $RSYNC_END ]

do

    # check MODE and if restore MODE, then swap source and destination directories
    case "$MODE" in
        'b')
            # normal backup MODE
            echo "`tput rev`Running backup:  ${BACKUP_NAME[$RSYNC_RUNNING]}`tput sgr0`"

            # set archive path and name
            ARCHIVE_PATH="${DEST_ARRAY[$RSYNC_RUNNING]::-1}-`date "+archive-%Y-%m-%d-%H.%M.%S"`"
            ;;

        'r')
            # restore MODE, need to swap source and destination

            # set archive path and name
            # (note, DEST_ARRAY is already up one directory level, so don't do it again here)
            ARCHIVE_PATH="${SRC_ARRAY[$RSYNC_RUNNING]::-1}-`date "+archive-%Y-%m-%d-%H.%M.%S"`"
            SWAPPATH=${SRC_ARRAY[$RSYNC_RUNNING]}
            SRC_ARRAY[$RSYNC_RUNNING]=${DEST_ARRAY[$RSYNC_RUNNING]}
            DEST_ARRAY[$RSYNC_RUNNING]=$SWAPPATH

            echo "`tput rev`Running RESTORE:  ${BACKUP_NAME[$RSYNC_RUNNING]}`tput sgr0`"
            ;;

        *)
            # error condition, should never occur since we validated input above
            echo "Error with $MODE_TEXT MODE:  $MODE"
            exit 1
            ;;
    esac


    # create the archive directory now
    mkdir -p $ARCHIVE_PATH

    # error log path & filename
    ERROR_LOG="$ARCHIVE_PATH/.rsync-error.log"

    # log file path & filename
    LOG_FILE="$ARCHIVE_PATH/.rsync.log"

    # reset to no error condition
    RSYNC_ERROR="n"

    # next line will create the log file $LOG_FILE (no -a switch on tee)
    echo | tee "$LOG_FILE"
    echo "These are the settings we will use for $MODE_TEXT number:  $RSYNC_RUNNING" | tee -a "$LOG_FILE"
    echo | tee -a "$LOG_FILE"
    echo "${MODE_TEXT^} Name:       "${BACKUP_NAME[$RSYNC_RUNNING]} | tee -a "$LOG_FILE"
    echo "Source Path:       "${SRC_ARRAY[$RSYNC_RUNNING]} | tee -a "$LOG_FILE"
    echo "Destination Path:  "${DEST_ARRAY[$RSYNC_RUNNING]} | tee -a "$LOG_FILE"
    echo "Archive Path:      "$ARCHIVE_PATH | tee -a "$LOG_FILE"
    echo "Log file:          "$LOG_FILE | tee -a "$LOG_FILE"
    echo "Error Log:         "$ERROR_LOG | tee -a "$LOG_FILE"
    echo "Rsync Switches:    "${RSYNC_SW_ARRAY[$RSYNC_RUNNING]} --backup-dir \"$ARCHIVE_PATH\" | tee -a "$LOG_FILE"
    echo | tee -a "$LOG_FILE"
    echo -n "Started at:        " ; date | tee -a "$LOG_FILE"
    echo | tee -a "$LOG_FILE"

    # menu line
    # save cursor position
    tput sc

    # go to 3rd line, 88 characters in
    tput cup 2 88
    echo -n "Current Backup:  `tput smul`$RSYNC_RUNNING`tput rmul`  `tput smul`${BACKUP_NAME[$RSYNC_RUNNING]}`tput rmul`"
    # clear line from cursor to end of line
    tput el

    # display the source path
    # go to 4th line, 40 characters in
    tput cup 3 40
    echo -n "Source Path:       "`tput smul`${SRC_ARRAY[$RSYNC_RUNNING]}`tput rmul`
    # clear line from cursor to end of line
    tput el

    # display the destination path
    # go to 5th line, 40 characters in
    tput cup 4 40
    echo -n "Destination Path:  "`tput smul`${DEST_ARRAY[$RSYNC_RUNNING]}`tput rmul`
    # clear line from cursor to end of line
    tput el

    # restore cursor position
    tput rc

    #
    # RSYNC HERE! back quoting the double quotes makes rsync work with file names containing spaces
    #

    # (don't need to use sudo here because we made sure the script is in sudo)
    eval $RSYNC_PATH ${RSYNC_SW_ARRAY[$RSYNC_RUNNING]} \
        --backup-dir \"$ARCHIVE_PATH\" \
        \"${SRC_ARRAY[$RSYNC_RUNNING]}\" \"${DEST_ARRAY[$RSYNC_RUNNING]}\" 2>"$ERROR_LOG" | tee -a "$LOG_FILE"

    # output time and date stamp for the end of the log file
    echo | tee -a "$LOG_FILE"
    date | tee -a "$LOG_FILE"

    # Close error log so we can cat it below ** $LOG_FILE is now closed!
    exec 2>&-

    # Leave a zero size file with a system timestamp to show when we completed
    touch "${DEST_ARRAY[$RSYNC_RUNNING]}".latest-rsync-date

    # make ericswanson:staff owner of the backups
    # destination path
    chown 501:20 "${DEST_ARRAY[$RSYNC_RUNNING]}"
    # archive path
    chown 501:20 "$ARCHIVE_PATH"
    # log file
    chown 501:20 "$LOG_FILE"
    # error log
    chown 501:20 "$ERROR_LOG"

    # Check error log for errors
    if [ -s "$ERROR_LOG" ];
    then
        # Rsync exited with errors if error log file contains anything
        echo
        echo "RSYNC EXITED WITH ERRORS, CHECK THE LOG FILES"
        echo

        # menu line
        # save cursor position
        tput sc
        # go to 1st line, 26 characters in
        tput cup 0 26
        echo -n "`tput blink`RSYNC ERROR(S)`tput sgr0`"
        # restore cursor position
        tput rc
        # write backup name to error log to display at end
        # echo ${BACKUP_NAME[$RSYNC_RUNNING]}>>$BACKUP_ERRORS
        echo "${MODE_TEXT^} Name:       "${BACKUP_NAME[$RSYNC_RUNNING]}>>$BACKUP_ERRORS
        echo "Source Path:       "${SRC_ARRAY[$RSYNC_RUNNING]}>>$BACKUP_ERRORS
        echo "Destination Path:  "${DEST_ARRAY[$RSYNC_RUNNING]}>>$BACKUP_ERRORS
        echo "Archive Path:      "$ARCHIVE_PATH>>$BACKUP_ERRORS
        echo "Log file:          "$LOG_FILE>>$BACKUP_ERRORS
        echo "Error Log:         "$ERROR_LOG>>$BACKUP_ERRORS
        echo "Rsync Switches:    "${RSYNC_SW_ARRAY[$RSYNC_RUNNING]} --backup-dir \"$ARCHIVE_PATH\">>$BACKUP_ERRORS
        echo>>$BACKUP_ERRORS
        cat "$ERROR_LOG">>$BACKUP_ERRORS
        echo>>$BACKUP_ERRORS

        # RSYNC_ERROR related only to this current rsync run
        RSYNC_ERROR="y"
        # RSYNC_ANY_ERRORs applies for any backup run, not just the current one
        RSYNC_ANY_ERRORs="y"

        echo "=== ERROR LOG ==="
        cat "$ERROR_LOG"
        echo "=== END OF ERROR LOG ==="
        echo
        echo "Emailing error log file to $EMAIL."
        echo
        mail -s "RSYNC COMPLETED WITH ERRORS for ${BACKUP_NAME[$RSYNC_RUNNING]}" $EMAIL <"$ERROR_LOG"

    else
        # No errors from exit status if error log file is empty
        echo
        echo "Rsync completed successfully."
        echo
        # No errors
        echo "Emailing log file to $EMAIL."
        echo
        mail -s "rsync completed successfully for ${BACKUP_NAME[$RSYNC_RUNNING]}" $EMAIL <"$LOG_FILE"

    fi

    # Find the size of the archive folder
    ARCHIVE_SIZE=`du -hs $ARCHIVE_PATH | cut -f 1`

    # Remove the leading space
    ARCHIVE_SIZE=`echo "${ARCHIVE_SIZE// /}"`

    echo "Archive folder size: $ARCHIVE_SIZE"

    ARCHIVE_RENAME=$ARCHIVE_PATH"_("$ARCHIVE_SIZE")"

    echo "Renaming archive folder to: $ARCHIVE_RENAME"
    mv "$ARCHIVE_PATH" "$ARCHIVE_RENAME"
    echo

    # increment rsync pointer to next backup
    ((RSYNC_RUNNING++))
done

#
# End of program cleanup
#

# turn off scrolling region
printf "\033[r"

# restore saved terminal screen (switch back to primary terminal screen)
sleep 5
tput rmcup

echo "All selected $MODE_TEXT from the set `tput smul`${SRC_DEST_FILE##*/}`tput rmul` have been run."
echo

# were there any rsync errors noted?
if [ $RSYNC_ANY_ERRORs = "y" ]
then
    # there were errors in one or more backups
    tput rev
    tput blink
    echo "ONE OR MORE $MODE_TEXT HAD ERRORS, CHECK YOUR LOGS!" | awk '{print toupper($0)}'
    tput sgr0
    cat $BACKUP_ERRORS
    echo
else
    # no errors detected
    echo "`tput smul`No errors`tput rmul` were reported during $MODE_TEXT."
fi

echo
echo -n "Completion time:  " ; date
echo

# delete temp file containing list of any backups with rsync errors
if [[ -f $BACKUP_ERRORS ]]
then
    #delete the file
    rm $BACKUP_ERRORS
fi

# debugging: turn off echo commands after executing them (set -x)
set +x

exit 0