#!/usr/bin/bash
#
# <umount>/usr/local/sbin/pam-umount.sh %(USER) %(USERUID) %(MNTPT)</umount>'

set -eu

usr="$1"
uid="$2"
mtp="$3"
slce="system-virtiofs.slice"
slp=false

shutdownVMs(){
    local VM
    for VM in $(sudo -u $usr XDG_RUNTIME_DIR="/run/user/$uid" \
		     XDG_CONFIG_HOME="/var/tmp/vm/$uid" \
		     XDG_CACHE_HOME="/var/cache/user/$uid/" \
		     virsh list --state-running | \
		    sed -nE "s/.*\s+(\S+)\s+running/\1/p") ; do
	sudo -u $usr XDG_RUNTIME_DIR="/run/user/$uid" \
	     XDG_CONFIG_HOME="/var/tmp/vm/$uid" \
	     XDG_CACHE_HOME="/var/cache/user/$uid/" \
	     virsh destroy "$VM" 2>&1 | systemd-cat || true
	slp=true
    done
}

######################

## This is the first mount we need to get rid of:
if [[ "$mtp" =~ "/lmn/media/$usr/share" ]] && [[ -d "/run/user/$uid" ]] ; then
    shutdownVMs
    [[ "$slp" = true ]] && sleep 5 # leave some time to write caches …
    sudo -u ${usr} killall gvfsd | systemd-cat
    sudo -u ${usr} killall dbus-daemon | systemd-cat
    systemctl -q is-active "$slce" && systemctl kill "$slce"
    # debug to find processes blocking umount:
    # lsof >> /var/log/lsof.log
fi

## Just umount:
exec umount "$mtp"
