#!/bin/bash

source /opt/scripts_local/shared_functions.sh

WATCH_DIR=/mnt/union/home/denis/onedrive/inbox

file_removed() {
    MSG="$2 has been removed from $1"
    echo "$MSG"
    log2file "$MSG"
    #xmessage "$2 was removed from $1" &
}

file_modified() {
    MSG="$2 has been modified in $1"
    echo "$MSG"
    log2file "$MSG"
    # TIMESTAMP=`date`
    # echo "[$TIMESTAMP]: The file $1$2 was modified" >> monitor_log
}

file_created() {
  MY_DIR="$1"
  MY_FILE="$2"
  if grep -q kobo <<<"$MY_DIR"; then
    rclone move "$WATCH_DIR/kobo/" ggl_denis:kobo_upload
  elif grep -q torrent <<<"$MY_DIR"; then
    rsync -avP "$WATCH_DIR/torrent/" vmx-load.swallow-grue.ts.net:/mnt/inbox/torrent --remove-source-files
  fi
  # TIMESTAMP=`date`
  # echo "[$TIMESTAMP]: The file $1$2 was created" >> monitor_log
}

log2file() {
  echo "$1" > /opt/ionotify.log
}

inotifywait -q -m -r -e modify,delete,create "$WATCH_DIR" | while read DIRECTORY EVENT FILE; do
    case $EVENT in
        MODIFY*)
            file_modified "$DIRECTORY" "$FILE"
            ;;
        CREATE*)
            file_created "$DIRECTORY" "$FILE"
            ;;
        DELETE*)
            file_removed "$DIRECTORY" "$FILE"
            ;;
    esac
done