#!/system/bin/sh

export NO_MAGISK=0
export MODPATH=@MODPATH@

if [[ -d /dev/tmp/magisk_img/$(basename ${MODPATH}) ]]; then
	OVERLAY_PATH=/dev/tmp/magisk_img/$(basename ${MODPATH})/system/fonts
elif [[ -d /dev/tmp/magisk_merge_img/$(basename ${MODPATH}) ]]; then
	OVERLAY_PATH=/dev/tmp/magisk_merge_img/$(basename ${MODPATH})/system/fonts
else
	OVERLAY_PATH=${MODPATH}/system/fonts
	[[ "${MODPATH}" != "/sbin/.core/"* ]] && NO_MAGISK=1
fi

FONTPATH=${MODPATH}/system/fonts

FONTFILES="Roboto-BlackItalic.ttf
Roboto-Black.ttf
Roboto-BoldItalic.ttf
Roboto-Bold.ttf
RobotoCondensed-BoldItalic.ttf
RobotoCondensed-Bold.ttf
RobotoCondensed-Italic.ttf
RobotoCondensed-LightItalic.ttf
RobotoCondensed-Light.ttf
RobotoCondensed-Regular.ttf
Roboto-Italic.ttf
Roboto-LightItalic.ttf
Roboto-Light.ttf
Roboto-MediumItalic.ttf
Roboto-Medium.ttf
Roboto-Regular.ttf
Roboto-ThinItalic.ttf
Roboto-Thin.ttf"

error () {
	echo "!! ${@}"
	exit 1
}

backup_font () {
	if [ ! -d /system/fonts/Original ]; then
		echo "Backup original Fonts"
		mkdir -p /system/fonts/Original

		for font in ${FONTFILES}; do
			cp /system/fonts/${font} /system/fonts/Original/
		done
	fi
}

reset_font () {
	echo "Restoring original Font"

	if [ ${NO_MAGISK} -eq 0 ]; then
		for font in ${FONTFILES}; do
			rm -f ${FONTPATH}/${font}
		done
	else
		for font in ${FONTFILES}; do
			cp /system/fonts/Original/${font} /system/fonts/
		done

		rm -rf /system/fonts/Original
	fi
}

set_font () {
	echo "Setting Font ${1}"

	if [ ${NO_MAGISK} -eq 0 ]; then
		if [ -f ${OVERLAY_PATH}/NanoDroid/${1}.ttf ]; then
			for font in ${FONTFILES}; do
				ln -sf ${FONTPATH}/NanoDroid/${1}.ttf \
					${OVERLAY_PATH}/${font} || \
					error "Failed to apply Font ${1}"
			done
		else
			error "Font ${1} does not exist"
		fi
	else
		backup_font

		if [ -f /system/fonts/NanoDroid/${1}.ttf ]; then
			for font in ${FONTFILES}; do
				ln -sf /system/fonts/NanoDroid/${1}.ttf \
					/system/fonts/${font} || \
					error "Failed to apply Font ${1}"
			done
		else
			error "Font ${1} does not exist"
		fi
	fi

	echo "Reboot to apply Font"
}

[[ $(whoami) != "root" ]] && error "not running as root"

case ${1} in
	-s | --set )
		set_font "${2}"
	;;

	-r | --reset )
		reset_font
	;;

	* )
		echo "nanodroid-font
Change System font

Usage: nanodroid-font [opt] [font]

where [opt] can be:
  -s, --set [font]		set Font
  -r, --reset			restore Original Font

where [font] can be:
  FAST				FAST RMX Game Font
  NintendoLabo			NintendoLabo Logo/Packaging Font
  NintendoSwitch		NintendoSwitch OS Font
  Splatoon2			Splatoon2 Game Font
  SuperMarioMaker		Super Mario Maker Game Font
  SuperMario			Super Mario (World) Game Font"
	;;
esac
