65 lines
2.0 KiB
Bash
Executable File
65 lines
2.0 KiB
Bash
Executable File
#!/usr/bin/env bash
|
|
# Watch multiple directories
|
|
WATCH_DIRS=("/tmp" "/config/Fiscality/workspace")
|
|
|
|
export DISPLAY=${DISPLAY:-:1}
|
|
export XAUTHORITY=${XAUTHORITY:-/home/abc/.Xauthority}
|
|
LAST_SCAN_STATE_FILE="/tmp/.filewatcher_state"
|
|
LOG_FILE="/tmp/filewatcher.log"
|
|
|
|
# Allow abc user access to X
|
|
xhost +SI:localuser:abc >/dev/null 2>&1 || true
|
|
|
|
# Load previous seen files
|
|
declare -A seen
|
|
if [ -f "$LAST_SCAN_STATE_FILE" ]; then
|
|
while IFS= read -r f; do
|
|
[ -n "$f" ] && seen["$f"]=1
|
|
done < "$LAST_SCAN_STATE_FILE"
|
|
fi
|
|
|
|
persist_seen() {
|
|
: > "$LAST_SCAN_STATE_FILE"
|
|
for f in "${!seen[@]}"; do
|
|
printf '%s\n' "$f" >> "$LAST_SCAN_STATE_FILE"
|
|
done
|
|
}
|
|
|
|
echo "$(date): File watcher started, watching: ${WATCH_DIRS[*]}" >> "$LOG_FILE"
|
|
|
|
while true; do
|
|
# Iterate through all watched directories
|
|
for WATCH_DIR in "${WATCH_DIRS[@]}"; do
|
|
# Skip if directory doesn't exist yet
|
|
if [ ! -d "$WATCH_DIR" ]; then
|
|
echo "$(date): Directory $WATCH_DIR does not exist yet" >> "$LOG_FILE"
|
|
continue
|
|
fi
|
|
|
|
# Iterate over every entry in the directory
|
|
for file in "$WATCH_DIR"/*; do
|
|
[ -f "$file" ] || continue # only regular files
|
|
# skip our own state file if inside the watched dir
|
|
[ "$file" = "$LAST_SCAN_STATE_FILE" ] && continue
|
|
|
|
if [ -z "${seen["$file"]}" ]; then
|
|
# new file found
|
|
echo "$(date): New file detected: $file" >> "$LOG_FILE"
|
|
seen["$file"]=1
|
|
# Open with the default app (xdg-open) as user abc
|
|
if command -v gosu >/dev/null 2>&1; then
|
|
gosu abc env DISPLAY="$DISPLAY" XAUTHORITY="$XAUTHORITY" \
|
|
nohup xdg-open -- "$file" >/dev/null 2>&1 &
|
|
echo "$(date): Opened $file with xdg-open (gosu)" >> "$LOG_FILE"
|
|
else
|
|
# fallback
|
|
su -s /bin/bash abc -c "env DISPLAY='$DISPLAY' XAUTHORITY='$XAUTHORITY' nohup xdg-open -- '$file' >/dev/null 2>&1" || true
|
|
echo "$(date): Opened $file with xdg-open (su)" >> "$LOG_FILE"
|
|
fi
|
|
fi
|
|
done
|
|
done
|
|
|
|
persist_seen
|
|
sleep 2
|
|
done |