#!/bin/bash
# vim: cindent:shiftwidth=4:tabstop=4:smarttab:textwidth=100

set -o posix
set -o errexit
set -o pipefail
set -o nounset
#set -o xtrace

shopt -s nullglob

#$title$ filesystem error
#$check$ lost+found directory present, no leftover fsck files, !errors_count
#$ref$ mklost+found(8), e2fsck(8)
#$author$ Rafal Rzeczkowski
#$version$ 0.7.0

level_check long

#CHANGELOG
#0.5.0	create an initial version
#0.5.1	enumerate non-regular files in lost+found too
#0.6.0	scan for non-zero ext4 errors_count
#0.7.0	update code style

echodebug 'ext4 system error scan:'
if [[ -d /sys/fs/ext4 ]]; then
	pushd /sys/fs/ext4 >/dev/null
	for dev in *; do
		if [[ ! -s $dev/errors_count ]]; then
			continue
		fi
		errors_count=$(<"$dev/errors_count")
		if [[ $errors_count -eq 0 ]]; then
			echodebug "$dev OK"
		else
			error_plural=$(plural_text "$errors_count" error)
			fail critical "$errors_count ext4 $error_plural on $dev"
			exit
		fi
	done
	popd >/dev/null
fi

mounts=($(df --portability --all --print-type |
	awk '{if ($2~/^ext[0-9]$/) print $7}'))

echodebug 'ext4 lost+found directory verification:'
for mount in "${mounts[@]}"; do
	lost_found_dir="$mount/lost+found"
	if [[ ! -d "$lost_found_dir" ]]; then
		fail caution "lost+found directory missing under mountpoint $mount"
		helpmsg 'use mklost+found to create'
		exit
	fi

	IFS=$'\n' lost_files=($(find "$lost_found_dir" -xdev -mindepth 1 -maxdepth 1))

	if [[ ${#lost_files[@]} -gt 0 ]]; then
		file_plural=$(plural_text ${#lost_files[@]} file)
		fail warning "${#lost_files[@]} lost $file_plural found in lost+found directory under $mount"
		helpmsg 'examine files for useful content and delete them; investigate the origin of corruption'
		exit
	fi

	echodebug "$mount OK"
done

ok
