{ coreutils
, stdenv
, writeShellScriptBin
}:
let PATH = stdenv.lib.concatStringsSep ":" [ "${coreutils}/bin" ];
in
writeShellScriptBin "swaplist" ''
  # SYNTAX:
  # DESCRIPTION: print sorted swap usage of processes using it
  export PATH=${PATH}
  lastpid=
  swap=0
  sudo grep -H '^Swap:' /proc/*/smaps 2>/dev/null |
  while IFS=: read -r file x size x
   do
          pid=''${file#/proc/}
          pid=''${pid%/smaps}
          size=''${size% kB}
          size=''${size##* }
          if test "$pid" = "$lastpid"
           then swap=$(( swap + size ))
           else
                  if test "$swap" -gt 0
                   then printf "%u pid=%u cmd=%s\n" "$swap" "$lastpid" "$(tr '\000' ' ' </proc/"$lastpid"/cmdline)"
                   fi
                  if test "$pid" = self
                   then break
                   else
                          lastpid=$pid
                          swap=$size
                   fi
           fi
   done |
  sort -nk1,1
''