#!/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

set -o errexit
set -o nounset
set -o pipefail
set -o errtrace
shopt -s inherit_errexit
shopt -s shift_verbose

## The '/tmp' below is a PATTERN matched against mount output to find
## Calamares' mounts, not a temporary path this script creates.
## style-ok: no-tmp-hardcode

printf '%s\n' "$0: START"

if [ ! "$(id -u)" = "0" ]; then
  printf '%s\n' "$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
  mnt=$(printf '%s\n' "${line}" | awk '{print $2}')
  if [[ "${mnt}" != *"/tmp"* || "${mnt}" != *"/calamares"* ]]; then
    continue
  fi
  printf '%s\n' "umount ${mnt}"
  umount "${mnt}"
done <<< "${reverse_proc_mounts}"

printf '%s\n' "$0: DONE"
