#!/bin/bash
# --umount is invoked from ExecStopPost after systemd has stopped the cgroup.
# Without arguments this asks systemd to stop the service.

if [ "${1:-}" = "--umount" ]; then
  state=/run/umgrid/mounts
  if [ -f "$state" ]; then
    mapfile -t lines <"$state"
    for ((i=${#lines[@]}-1; i>=0; i--)); do
      mnt=${lines[$i]}
      [ -n "$mnt" ] || continue
      if mountpoint -q "$mnt"; then
        umount "$mnt" || umount -l "$mnt" || echo "umgrid-stop: umount failed $mnt" >&2
      fi
    done
    rm -f "$state"
  fi
  exit 0
fi

if [ -d /run/systemd/system ]; then
  exec systemctl stop umgrid.service
fi
echo "umgrid-stop: systemd is not running" >&2
exit 1
