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

set -e

readonly PREREQ=""

prereqs() {
	echo "${PREREQ}"
}

case "${1}" in
prereqs)
	prereqs
	exit 0
	;;
esac

if ischroot; then
	echo "not exec deepin-fix-init in chroot"
	exit 0
fi

. /usr/share/initramfs-tools/hook-functions

copy_exec /usr/bin/deepin-fix-init /bin/
copy_file file /usr/lib/terminfo/l/linux

copy_exec /bin/fbterm /bin/
#copy_exec /bin/dialog /bin/
copy_exec /bin/gettext /bin/
copy_file file /usr/share/terminfo/f/fbterm
copy_file file /usr/share/fonts/truetype/unifont/unifont.ttf
#copy_file file /usr/lib/locale/locale-archive
copy_file file /usr/share/locale/fix-init-locale-archive
copy_file file /etc/default/locale
copy_file file /bin/gettext.sh

# load locale config
[ -f /etc/default/locale ] && . /etc/default/locale

get_locale_arr() {
	if [ -z "$LANG" ]; then
		return
	fi
	# zh_CN.UTF-8
	echo $LANG
	# trim right .*
	local lang=${LANG%.*}
	# zh_CN
	echo $lang
	# trim right _*
	lang=${LANG%_*}
	# zh
	echo $lang
}

find_file() {
	local pattern="$1"
	for l in $(get_locale_arr); do
		local f=${pattern/@lang/$l}
		if [ -f "$f" ]; then
			echo "$f"
			return
		fi
	done
}

dialog_mo=$(find_file /usr/share/locale/@lang/LC_MESSAGES/dialog.mo)
if [ -f "$dialog_mo" ]; then
	copy_file file "$dialog_mo"
else
	echo WARN: no found dialog.mo >&2
fi

fix_init_mo=$(find_file /usr/share/locale/@lang/LC_MESSAGES/deepin-fix-init.mo)
if [ -f "$fix_init_mo" ]; then
	copy_file file "$fix_init_mo"
else
	echo WARN: no found deepin-fix-init.mo >&2
fi

get_mount_point_dev() {
        findmnt --target "$1" -n -f -v | awk '{print $2}'
}
tmp_file=$(mktemp deepin-fix-init-XXXXXX)
fix_init_root_dev=$(get_mount_point_dev /)
fix_init_root_fstype=$(blkid -o value -s TYPE "$fix_init_root_dev")
echo "ROOT_DEV=$fix_init_root_dev" >>"$tmp_file"
echo "ROOT_TYPE=$fix_init_root_fstype" >>"$tmp_file"
copy_file file "$tmp_file" /etc/deepin-fix-init.cfg


