#!/bin/bash

# Lazy-unmount gvfsd-fuse filesystems before suspend/hibernate to prevent the
# kernel's process freeze from timing out. FUSE daemons (like gvfsd-fuse from
# Nautilus) can block in uninterruptible sleep during freeze, causing suspend
# to silently fail. After wake, restart gvfs so the FUSE mount is restored.

if [[ $1 == "pre" ]]; then
  while IFS=' ' read -r _ mountpoint fstype _; do
    if [[ $fstype == fuse.gvfsd-fuse ]]; then
      mountpoint=$(printf '%b' "$mountpoint")
      fusermount3 -uz "$mountpoint" 2>/dev/null || fusermount -uz "$mountpoint" 2>/dev/null || true
    fi
  done < /proc/mounts
fi

if [[ $1 == "post" ]]; then
  # Hand the restart to a timer unit: systemd kills anything this hook leaves behind when the
  # sleep service ends, and user.slice stays frozen until the hook returns.
  for uid_dir in /run/user/*; do
    uid=$(basename "$uid_dir")
    if [[ -S $uid_dir/bus ]]; then
      systemd-run --quiet --no-block --collect --on-active=5 --timer-property=AccuracySec=1s --uid="$uid" \
        --setenv=DBUS_SESSION_BUS_ADDRESS="unix:path=$uid_dir/bus" \
        --setenv=XDG_RUNTIME_DIR="$uid_dir" \
        systemctl --user restart gvfs-daemon.service 2>/dev/null || true
    fi
  done
fi
