diff --git a/nixos/common/software/cli/scripts/btrfs-backup.sh b/nixos/common/software/cli/scripts/btrfs-backup.sh index 633479b8..9e8d06bd 100755 --- a/nixos/common/software/cli/scripts/btrfs-backup.sh +++ b/nixos/common/software/cli/scripts/btrfs-backup.sh @@ -32,6 +32,36 @@ if ! command -v snapper >/dev/null 2>&1 || \ exit 1 fi +# Lock file handling +LOCK_FILE="/var/run/btrfs-backup-${1}.lock" + +# Lock file creation with cleanup +cleanup_lock() { + rm -f "$LOCK_FILE" +} + +create_lock() { + if [ -e "$LOCK_FILE" ]; then + # Check if the process is still running + if pid=$(cat "$LOCK_FILE" 2>/dev/null) && kill -0 "$pid" 2>/dev/null; then + echo "ERROR: Another backup process (PID: $pid) is already running" + exit 1 + else + # Lock file exists but process is not running, remove stale lock + rm -f "$LOCK_FILE" + fi + fi + + # Create new lock file with current PID + echo $$ > "$LOCK_FILE" + + # Ensure lock file is removed on script exit + trap cleanup_lock EXIT +} + +# Create lock file +create_lock + # Help function show_help() { cat << EOF @@ -117,12 +147,16 @@ cleanup() { sudo snapper -c "$SNAPPER_CONFIG" delete "$NEW_SNAPSHOT" || true fi fi + + # Remove lock file + cleanup_lock + exit $exit_code } # Set up traps trap 'error_handler ${LINENO} $?' ERR -trap cleanup EXIT +trap cleanup EXIT INT TERM # Get the actual snapshot location from snapper config SOURCE_PATH=$(sudo snapper -c "$SNAPPER_CONFIG" get-config | grep '^SUBVOLUME' | cut -d'=' -f2 | tr -d '"'| awk {'print $3'})