# This file is part of the 'dragora-installer'.
#
# Purpose: Make mount points and mount non-root filesystems from fstab.

# Make declared mount points from fstab, exclude:
# commentaries, root, and possible swapfile.
makeMountPoints()
{
    grep -E -v '^#|swap|/ ' "${SUBTMPDIR}/fstab" | \
     awk '{ print substr($2,2) }' | while read -r directory
      do
          test -n "$directory" || continue

          # Make sure to translate converted blank spaces (\040)
          # into common spaces for directory creation (see MakeFS)
          directory="$(printf '%s' "$directory" | tr '\\040' ' ')"

          if test ! -d "/media/dragora-root/${directory}"
          then
              mkdir -p -- "/media/dragora-root/${directory}"
          fi
      done
}

mountNonRoot()
{
    if test -s "${SUBTMPDIR}/fstab"
    then
        awk '!/^#/ && !/\/ / && !/fd0/ && !/swap/ { print $1,$2 }' \
         "${SUBTMPDIR}/fstab" | while IFS=" " read -r device mntpoint
         do
             umount "$device" > /dev/null 2>&1 || true

             mntpoint="$(printf '%s' "$mntpoint" | tr '\\040' ' ')"
             mntpoint="/media/dragora-root/${mntpoint}"

             echo ""
             umount -v "$device" || true
             mount -v "$device" "$mntpoint" || exit $?
             sleep 2
         done
    fi
}

dialog --colors \
 --backtitle "\\ZbNon-root partition(s)" \
 --title "NON-ROOT MOUNTS" --sleep 2 \
 --infobox "Preparing to mount the rest of the file systems..." 3 54

makeMountPoints
mountNonRoot

if test ! -e /media/dragora-root/etc/fstab
then
    # Copy fstab into the root partition
    mkdir -p -- /media/dragora-root/etc || true
    cp -f -- "${SUBTMPDIR}/fstab" /media/dragora-root/etc/
else
    # Offer the possibility to overwrite the fstab file only if
    # there is a difference, since there is no point in asking to
    # overwrite the (newly) created and copied file

    if test \
"$(cmp -s "${SUBTMPDIR}/fstab" /media/dragora-root/etc/fstab; printf $?)" = "1"
    then
        dialog --no-shadow --colors \
         --backtitle "\\ZbFile system table (fstab)" \
         --title "EXISTING FILE SYSTEM TABLE" \
         --cr-wrap --yesno \
"A file system table already exists on the mounted root partition:
    /media/dragora-root/etc/fstab

Overwrite this file only if:
  - This is a new installation.
  - You are installing a new kernel image.
  - To create a boot disk with a new kernel.

In this case, you must configure the system to boot properly.

Do not overwrite the file system table if you are adding
software to the existing system...

Do you want to replace the existing fstab with the new one?
" 19 69 || { unset makeMountPoints mountNonRoot ; return 0; }

        mkdir -p -- /media/dragora-root/etc || true
        cp -f -- "${SUBTMPDIR}/fstab" /media/dragora-root/etc/
    fi
fi

unset makeMountPoints mountNonRoot

