#!/bin/sh
# SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd.
#
# SPDX-License-Identifier: GPL-3.0-or-later

# Script to perform early init fix tasks in initramfs environment.
# It checks boot conditions, loads locale settings and runs the main tool.
set -e

readonly PREREQ="plymouth"

# Function to list prerequisites
prereqs() {
	echo "${PREREQ}"
}

# Check command line arguments for 'prereqs'
case "${1}" in
prereqs)
	prereqs
	exit 0
	;;
esac

# Exit if break is set (e.g. due to kernel parameter)
if [ -n "$break" ]; then
	exit 0
fi

# Only run if system is booted locally
if [ "$BOOT" != local ] && [ "$BOOT" != ostree ]; then
	echo 'boot is not local or ostree, exit'
	exit 0
fi

is_mounted() {
    local mount_point="$1"
    local device mount_path fs_type options dump fsck_order

    [ -z "$mount_point" ] && return 1

    while read -r device mount_path fs_type options dump fsck_order; do
        if [ "$mount_path" = "$mount_point" ]; then
            return 0
        fi
    done < /proc/mounts

    return 1
}

# Function: setup_console
# Set up console device for UI output
setup_console() {
	unset IFS
	read -r console rest </proc/consoles
	if [ "${console}" = "tty0" ]; then
		console="tty1"
	fi
}

# Function: setup_locale
# Prepare locale environment
setup_locale() {
	mkdir -p /usr/lib/locale/
	if [ -f /usr/share/locale/fix-init-locale-archive ]; then
		mv /usr/share/locale/fix-init-locale-archive /usr/lib/locale/locale-archive
	fi

	if [ -f /etc/default/locale ]; then
		. /etc/default/locale
	else
		LANG=en_US
		LANGUAGE=en_US.UTF-8
	fi
	export LANG
	export LANGUAGE
}

# Function: launch_tool
# Launch deepin-fix-init on selected VT using fbterm
launch_tool() {
	if [ -x "/bin/fbterm" ]; then
		# Wait for display to be ready, must sleep for 15 seconds, otherwise the interface will not be refreshed.
		sleep 15
		sh -c "exec fbterm -s 20 -n unifont -- deepin-fix-init <> /dev/${console} 1>&0 2>&1"
	else
		# Wait for display to be ready
		udevadm settle --timeout=15
		sh -c "exec deepin-fix-init -d <> /dev/${console} 1>&0 2>&1"
	fi
}

# Main function
main() {
	setup_console
	setup_locale
	launch_tool
	printf '\033[2J\033[H' || true
	stty sane || true
}

# Run main function with all passed arguments
main "$@"
