#!/bin/bash

## When calamares errors out, it does not umount temporary mounts in the /tmp
## folder. It might be possible to configure that but keeping the mounts around
## can be useful to test-wise chroot into these for debugging purposes.
## Instead, this script is provided as a tool for developers to manually umount
## these folders so calamares can be restarted.
##
## Calamares does not show "erase disk" option if it previously failed without
## umounting the temporary mounts beforehand.
## https://github.com/calamares/calamares/issues/1258

echo "$0: START"

if [ ! "$(id -u)" = "0" ]; then
  echo "$0: Must be run as root! (sudo)" >&2
  exit 1
fi

reverse_proc_mounts=$(tac /proc/mounts)

while read -r line ; do
  if [ "$line" = "" ]; then
    continue
  fi
  b=$(echo "$line" | awk '{print $2}')
  c=$(echo "$b" | grep "/tmp")
  d=$(echo "$c" | grep "/calamares")
  if [ "$d" = "" ]; then
    continue
  fi
  echo umount "$d"
  umount "$d"
done <<< "$reverse_proc_mounts"

echo "$0: DONE"
