{ config, pkgs, lib, ... }:

{
  systemd.settings.Manager.DefaultTimeoutStopSec = lib.mkDefault "5s";

  systemd.services."user@".serviceConfig.TimeoutStopSec = lib.mkDefault "5s";

  powerManagement.powerDownCommands = ''
    # --- force-igpu ---
    # Use the Vfio to Integrated trick to turn off NVIDIA dgpu when in integrated mode
    if [[ $1 == "hibernate" ]] && ${pkgs.coreutils}/bin/lsmod | grep -q supergfxd; then
      ${pkgs.supergfxctl}/bin/supergfxctl -m Vfio || true
      sleep 1
    fi

    # --- keyboard-backlight ---
    # Turn off keyboard backlight before hibernate to prevent hang on power-off.
    if [[ $1 == "hibernate" ]]; then
      device=""
      for candidate in /sys/class/leds/*kbd_backlight*; do
        if [[ -e "$candidate" ]]; then
          device="$(${pkgs.coreutils}/bin/basename "$candidate")"
          break
        fi
      done
      if [[ -n "$device" ]]; then
        ${pkgs.brightnessctl}/bin/brightnessctl -d "$device" set 0 >/dev/null 2>&1 || true
      fi
    fi

    # --- unmount-fuse ---
    # Lazy-unmount gvfsd-fuse filesystems before suspend/hibernate
    while IFS=' ' read -r _ mountpoint fstype _; do
      if [[ $fstype == fuse.gvfsd-fuse ]]; then
        mountpoint=$(printf '%b' "$mountpoint")
        ${pkgs.fuse3}/bin/fusermount3 -uz "$mountpoint" 2>/dev/null || ${pkgs.fuse}/bin/fusermount -uz "$mountpoint" 2>/dev/null || true
      fi
    done < /proc/mounts
  '';

  powerManagement.resumeCommands = ''
    # --- force-igpu ---
    if ${pkgs.coreutils}/bin/lsmod | grep -q supergfxd; then
      sleep 4
      ${pkgs.supergfxctl}/bin/supergfxctl -m Vfio || true
      sleep 1
      ${pkgs.supergfxctl}/bin/supergfxctl -m Integrated || true
    fi

    # --- unmount-fuse ---
    (
      sleep 5
      for uid_dir in /run/user/*; do
        uid="$(${pkgs.coreutils}/bin/basename "$uid_dir")"
        if [[ -S $uid_dir/bus ]]; then
          sudo -u "#$uid" env \
            DBUS_SESSION_BUS_ADDRESS="unix:path=$uid_dir/bus" \
            XDG_RUNTIME_DIR="$uid_dir" \
            systemctl --user restart gvfs-daemon.service 2>/dev/null || true
        fi
      done
    ) &
  '';
}
