#!/usr/bin/with-contenv bash
# shellcheck shell=bash

# Check if inotify exists. If not, install it.
if  ! command -v inotifywait 2>&1 >/dev/null; then
	echo "No inotifywait found. install inotify tools"
	apk add inotify-tools	
fi

# define stuff that should be excluded some watches.
BASEEXCLUDE='.*\.swp|.*\.swx'

# the main function where all of the magic happens. takes 4 arguments:
# - the folder to watch
# - stuff to exclude
# - two arguments to replace things in the paths coming from inotify, to turn them into a path nextcloud understands.
detect(){
	WATCH=$1
	EXCLUDE=$2
	REPLACEIN=$3
	REPLACEWITH=$4

	echo "watching $WATCH and excluding $EXCLUDE"
	
	# this uses inotifywait to watch for changes
	# then it runs the code in the while block to handle file paths it spits out
	inotifywait -mre close_write,delete --format '%e|%w|%f' --exclude "$EXCLUDE" "$WATCH" | while read RAWEVENT
	do
		# inotifywait spits out the events like "eventtype|/directory|filename"
		# here we split them into it's three parts.
		IFS='|'
		read -a SPLITEVENT <<< "$RAWEVENT"

		EVENT=${SPLITEVENT[0]}
		DIR=${SPLITEVENT[1]}
		FILE=${SPLITEVENT[2]}

		# by default, scan the whole directory
		# we can't scan a file that's been deleted
		REPLACEDFILE=$DIR

		# if the event wasn't a delete, we append the filename
		# so we only scan the file that was changed.
		if [[ $EVENT != 'DELETE' ]]; then
		REPLACEDFILE+=$FILE
		fi

		# replace the beginning of the paths to the filename. 
		# inotify spits out the filesystem path
		# nextcloud expects the path relative to the user directory
		if [ -n "$REPLACEIN" ] && [ -n "$REPLACEWITH" ]; then
			REPLACEDFILE=${REPLACEDFILE/$REPLACEIN/$REPLACEWITH}
		fi

		# actually run the OCC command
		occ files:scan --path=\"$REPLACEDFILE\" --shallow
	done
}

# run the scan function on the folders I want scanned
detect /data/riksolo/files $BASEEXCLUDE /data/riksolo /riksolo 