#!/bin/sh
### BEGIN INIT INFO
# Provides:          checkallfs
# Required-Start:    mountvirtfs
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description: Check all the fstab filesystems.
### END INIT INFO

# shellcheck disable=SC1091
. /etc/default/rcS

# Early exit if fsck was not enabled in the configuration file.
[ "$ENABLE_ALL_FSCK" != yes ] && exit 0

echo "Checking all filesystems..."

#
# Remount rootfs as read-only
#
# We don't run fsck on the root fstab entry to avoid issues where /dev/root
# device placeholder is used. Even so, we still remount root in case there are
# other entries pointing to the actual root device.
rootmodeinitial=rw
grep -q "^/dev/root.*ro" /proc/mounts && rootmodeinitial=ro
if [ "$rootmodeinitial" = rw ]; then
  if ! mount -n -o remount,ro /; then
    echo
    echo "WARNING: Failed to remount rootfs read-only for fsck."
    echo
  fi
fi

#
# Activate the swap device(s) in /etc/fstab. This needs to be done
# before fsck, since fsck can be quite memory-hungry.
#
[ "$VERBOSE" != no ] && echo "Activating swap"
[ -x /sbin/swapon ] && swapon -a

#
# Handle fsck'ing the filesystems
#
fsck -R -C -A -y
if [ "$?" -gt 1 ]; then
  # NOTE: "failure" is defined as exiting with a return code of
  # 2 or larger.  A return code of 1 indicates that filesystem
  # errors were corrected but that the boot may proceed.
  echo
  echo "WARNING: fsck'ing the fstab filesystems failed. Proceed with caution!"
  echo
fi

#
# Return to initial root mode if remounted read-only.
#
if [ "$rootmodeinitial" = rw ]; then
  mount -n -o remount,$rootmodeinitial /
fi

exit 0
