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

BASE_DIR="/mypool1/data"
INPUT_DIR="$BASE_DIR/$1"
MY_SERVICE="bck_$1_mon.service"

# Check if a path is provided
if [ -z "$INPUT_DIR" ]; then
    echo "Usage: $0 <path>"
    exit 1
else
    # Check if the path exists
    if [ ! -d "$INPUT_DIR" ]; then
        echo "Error: Directory $INPUT_DIR does not exist."
        exit 1
    else
        echo "$INPUT_DIR exists proceeding"
        ROOT_SRC_DIR="$INPUT_DIR"
    fi
fi

bck_request() {
    echo "Calling path_3_levels for stripping and removing trailing subfolders from $1"
    path_3_levels $1
    echo "Backup flag set, stopping monitoring by stopping $MY_SERVICE"
    systemctl stop "$MY_SERVICE"
}

path_3_levels() {
    # Check if a path is provided
    if [ -z "$1" ]; then
        echo "Usage: $0 <path>"
        exit 1
    fi

    # Get the input path
    input_path="$1"

    # Remove trailing slashes (if any) to standardize the input
    input_path=$(echo "$input_path" | sed 's:/*$::')

    # Truncate the path to the first 3 levels
    truncated_path=$(echo "$input_path" | awk -F/ '{print FS $2"/"$3"/"$4}')


    # Set backup flag
    touch "$truncated_path/_NEEDS_BACKUP"
}

inotifywait -q -m -r -e modify,delete,create $ROOT_SRC_DIR | while read DIRECTORY EVENT FILE; do
    bck_request $DIRECTORY $FILE
done


