#!/bin/bash set -euo pipefail # premise: inotify listens for events (create) from media insertion, # as a background process. # If a new device is created in /media/$USER and it contains folder mca_logs sync logs # create a lockfile based on user id LOCKFILE="/tmp/usb_log_sync_$(id -u).lock" # If the PID in the lockfile is not running anymore remove else see if its running if [[ -e "$LOCKFILE" ]]; then if kill -0 "$(cat "$LOCKFILE" 2>/dev/null)" 2>/dev/null; then echo "Another instance is already running (PID $(cat "$LOCKFILE")). Exiting." >&2 exit 1 else echo "Removing stale lockfile from previous session..." rm -f "$LOCKFILE" fi fi # PID of current script echo "$$" > "$LOCKFILE" # Clean up on exit, terminare, interupt hangup trap 'rm -f "$LOCKFILE"; exit 0' INT TERM EXIT HUP # hide executions #exec 1>/dev/null #exec 2>/dev/null WATCHDIR="/media/$USER" inotifywait -m -e create "$WATCHDIR" --format "%f" | while read DIR; do MOUNTPOINT="$WATCHDIR/$DIR" #echo $MOUNTPOINT # drive is detected before full mount so wait upto 3 seconds for i in {1..30}; do # if newly inserted device has an mca_logs folder, trigger rsync if [[ -d "$MOUNTPOINT/mca_logs" ]]; then # where the logs are, relative to where the script is. SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" src="${SCRIPT_DIR}/../../logs" dst="$MOUNTPOINT/mca_logs" cd $src find . -type f -mtime -30 -print0 | rsync -av --files-from=- --from0 . "$dst/" break fi sleep 0.1 done done #keep it anyway for future use. #spawn process from mca.py on init #import subprocess #sync_script = os.path.join(os.path.dirname(__file__), "../../resources/scripts/synch2.sh") #subprocess.Popen([sync_script])