#!/bin/bash
# A script to perform incremental backups using rsync
# https://www.baeldung.com/linux/monitor-changes-directory-tree
set -o errexit
set -o nounset
set -o pipefail

export LOG_TAG="Rsync Increm Backup"
export LOG_PRIO=5
RCLONE_CONFIG_FILE=/opt/rclone/rclone.conf
SRC_DIR=scripts_local
DST_DIR=/opt/backup
SRC_DIR_PATH="/opt/$SRC_DIR"
DST_DIR_PATH="$DST_DIR$SRC_DIR_PATH"
readonly SOURCE_DIR="$SRC_DIR_PATH"
readonly BACKUP_DIR="SRC_DIR_PATH"
readonly DATETIME="$(date '+%Y-%m-%d_%H:%M:%S')"
readonly BACKUP_PATH="${BACKUP_DIR}/${DATETIME}"
readonly LATEST_LINK="${BACKUP_DIR}/latest"

file_modified() {
  TIMESTAMP=`date`
  # echo "[$TIMESTAMP]: The file $1$2 was modified" >> monitor_log
  logger -p $LOG_PRIO -t "$LOG_TAG" "[$TIMESTAMP]: The file $1$2 was modified"
  SUBPATH=$(echo "$1" | cut -d'/' -f6-)
  mkdir -p "${BACKUP_DIR}"
  rsync -av --delete \
    "${SOURCE_DIR}/" \
    --link-dest "${LATEST_LINK}" \
    --exclude=".cache" \
    "${BACKUP_PATH}"
  rm -rf "${LATEST_LINK}"
  ln -s "${BACKUP_PATH}" "${LATEST_LINK}"
}

inotifywait -q -m -r -e modify $ROOT_SRC_DIR | while read DIRECTORY EVENT FILE; do
    case $EVENT in
        MODIFY*)
            file_modified "$DIRECTORY" "$FILE"
            ;;
    esac
done