#!/bin/sh
#Copyright: 2026 Aitor <aitor@genuen.org>
#License: CC0-1.0
#Comment: oneshot; invoke with: sv once checkfs.sh

exec 2>&1

ebegin() { [ "${VERBOSE:-}" = no ] || echo "$@"; }
eend() { r=${1:-0}; shift || true; [ "$r" -eq 0 ] || [ "${VERBOSE:-}" = no ] || echo "$*" >&2; return "$r"; }
einfo() { [ "${VERBOSE:-}" = no ] || echo "$@"; }
ewarn() { echo "$@" >&2; }
eerror() { echo "$@" >&2; }

/usr/lib/runit-services/stage1/sv once cryptdisks || true


FSCK_LOGFILE=/var/log/fsck/checkfs
[ "$FSCKFIX" ] || FSCKFIX=no
. /lib/init/vars.sh
. /lib/init/mount-functions.sh

if command -v setterm >/dev/null 2>&1; then
	setterm=setterm
else
	setterm='true -- '
fi

trap "" INT
BAT=""
fscheck="yes"

if is_fastboot_active; then
	[ "$fscheck" = yes ] && ewarn "Fast boot enabled, so skipping file system check."
	fscheck=no
fi

if [ "$fscheck" = yes ] && [ ! "$BAT" ] && [ "$FSCKTYPES" != "none" ]; then
	if [ -f /forcefsck ] || grep -q -s -w -i "forcefsck" /proc/cmdline; then
		force="-f"
	else
		force=""
	fi
	if [ "$FSCKFIX" = yes ]; then fix="-y"; else fix="-a"; fi
	spinner="-C"
	case "$TERM" in
	  dumb|network|unknown|"") spinner="" ;;
	esac
	[ "$(uname -m)" = s390x ] && spinner=""
	FSCKTYPES_OPT=""
	[ "$FSCKTYPES" ] && FSCKTYPES_OPT="-t $FSCKTYPES"
	handle_failed_fsck() {
		eerror "File system check failed. Log: ${FSCK_LOGFILE}"
		ewarn "A maintenance shell will now be started. CONTROL-D continues boot."
		if ! sulogin --force $CONSOLE; then
			eerror "Attempt to start maintenance shell failed. Continuing in 5 seconds."
			sleep 5
		fi
	}
	ebegin "Checking file systems"
	$setterm --msg off
	if [ "$VERBOSE" = no ]; then
		logsave_best_effort fsck $spinner -T -M -A $fix $force $FSCKTYPES_OPT
	else
		logsave_best_effort fsck $spinner -V -T -M -A $fix $force $FSCKTYPES_OPT
	fi
	FSCKCODE=$?
	$setterm --msg on
	if [ "$FSCKCODE" -eq 32 ]; then
		eend 1 "code $FSCKCODE"
		ewarn "File system check was interrupted by user"
	elif [ "$FSCKCODE" -gt 1 ]; then
		eend 1 "code $FSCKCODE"
		handle_failed_fsck
	else
		eend 0
	fi
fi
rm -f /fastboot /forcefsck 2>/dev/null
exit 0
