#!/bin/bash
# https://www.baeldung.com/linux/monitor-changes-directory-tree

export LOG_TAG="Beltex Luca Upload"
export LOG_PRIO=5
RCLONE_CONFIG_FILE=/opt/rclone/rclone.conf
ROOT_SRC_DIR="/srv/smb/beltex/Luca"
ROOT_DST_DIR="o365:/LUCA-Gestcom"
RCLONE_LOG=/var/log/beltex_luca_upload.log
file_removed() {
    TIMESTAMP=`date`
    # echo "[$TIMESTAMP]: The file $1$2 was removed" >> monitor_log
    logger -p $LOG_PRIO -t "$LOG_TAG" "[$TIMESTAMP]: The file $1$2 was removed"
}

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"
}

file_created() {
    TIMESTAMP=`date`
    # echo "[$TIMESTAMP]: The file $1$2 was created" >> monitor_log
    logger -p $LOG_PRIO -t "$LOG_TAG" "[$TIMESTAMP]: The file $1$2 was created"
}

file_upload() {
    SUBPATH=$(echo "$1" | cut -d'/' -f6-)
    logger -p $LOG_PRIO -t "$LOG_TAG" "[$TIMESTAMP]: $SUBPATH"
    rclone copy --config "$RCLONE_CONFIG_FILE" \
        --ignore-size \
        --ignore-checksum \
        -vvv \
        --log-file "$RCLONE_LOG" \
        "$1$2"  "$ROOT_DST_DIR/$SUBPATH"
}

inotifywait -q -m -r -e modify,delete,create $ROOT_SRC_DIR | while read DIRECTORY EVENT FILE; do
    case $EVENT in
        MODIFY*)
            file_modified "$DIRECTORY" "$FILE"
            # if [[ "$FILE" =~ .*pdf$ ]]; then             # if suffix is '.rst'
            file_upload "$DIRECTORY" "$FILE"
            # fi
            ;;
        CREATE*)
            file_created "$DIRECTORY" "$FILE"
            # if [[ "$FILE" =~ .*pdf$ ]]; then             # if suffix is '.rst'
                file_upload "$DIRECTORY" "$FILE"
            # fi
            ;;
        DELETE*)
            file_removed "$DIRECTORY" "$FILE"
            ;;
    esac
done


