#!/bin/sh
### BEGIN INIT INFO
# Provides:            checkfs
# Required-Start:      checkroot hostname swap $time udev
# Required-Stop:
# Should-Start:
# Should-Stop:
# Default-Start:       S
# Default-Stop:
# Short-Description:   Check filesystems for errors
# X-Required:          true
### END INIT INFO

. /lib/lsb/init-functions
[ -z $container ] || exit 0

case "$1" in
  start)
    if [ -f /fastboot ] || grep -qwi 'fastboot' /proc/cmdline; then
      log_init_msg "Fastboot enabled - skipping fsck"
      log_success_msg
   
      exit 0
    fi

    if [ -f /forcefsck ] || grep -qwi 'forcefsck' /proc/cmdline; then
      log_init_msg "Checking file systems with force"
      force='-f'
    else
      log_init_msg 'Checking file systems'
    fi

    case "$FSCKFIX" in
      1|y|yes)
        fix='-y'
        ;;
      *)
        fix='-p'
        ;;
    esac

    case "$VERBOSE" in
      1|y|yes)
        echo
        fsck $force $fix -A -C -T -R
        ;;
      *)
        fsck $force $fix -A -T -R >/dev/null
        ;;
    esac

    status=$?

    if [ $status = 0 ]; then
      log_success_msg
    elif [ $status = 1 ]; then
      log_warning_msg

      echo
      echo "WARNING: File system errors were detected and repaired."
      echo
    elif [ $status = 2 -o $status = 3 ]; then
      log_warning_msg

      echo
      echo "WARNING: File system errors were detected and repaired."
      echo "The repairs require the system to be rebooted."
      echo
      echo "Press enter to reboot"
      read reboot
      reboot -f
    elif [ $status -gt 3 -a $status -lt 16 ]; then
      log_failure_msg

      echo
      echo "File system errors were detected, but could not be"
      echo "repaired automatically."
      echo
      echo "Press enter to halt"
      read halt
      /etc/init.d/halt stop
    else
      log_failure_msg

      echo
      echo "fsck exited with unexpected status: $status"
      echo
      echo "Press enter to halt"
      read halt
      /etc/init.d/halt stop
    fi
    ;;
  *)
    echo "Usage: $0 [start]"
    exit 1
    ;;
esac

exit 0
