#!/bin/bash
#make by G.R.H

if [ ! -f /usr/bin/mpv ]; then
	echo "Error: The necessary playback files are missing and the program cannot run."
	exit 1
fi
. /mnt/mod/ctrl/configs/key_config &>/dev/null
progdir="$(cd $(dirname "$0"); pwd)"
MODEL=$(head -n 1 /mnt/vendor/oem/board.ini)
case ${MODEL} in
	RG35xxH)
		HW="joy"
	;;
	*)
		HW="btn"
	;;
esac

KEY=99

pkill -f mpv
pkill -f evtest
mpv --really-quiet --image-display-duration=6000 "${progdir}/res/${HW}.png" &

while true
do
	Test_Button_A
	if [ "$?" -eq "10" ]; then
		pkill -f mpv
		mpv --really-quiet --image-display-duration=6000 "${progdir}/res/${HW}_A.png" &
		KEY=0
	fi
	Test_Button_B
	if [ "$?" -eq "10" ]; then
		pkill -f mpv
		mpv --really-quiet --image-display-duration=6000 "${progdir}/res/${HW}_B.png" &
		KEY=1
	fi
	Test_Button_Y
	if [ "$?" -eq "10" ]; then
		pkill -f mpv
		mpv --really-quiet --image-display-duration=6000 "${progdir}/res/${HW}_Y.png" &
		KEY=2
	fi
	Test_Button_X
	if [ "$?" -eq "10" ]; then
		pkill -f mpv
		mpv --really-quiet --image-display-duration=6000 "${progdir}/res/${HW}_X.png" &
		KEY=3
	fi
	Test_Button_L1
	if [ "$?" -eq "10" ]; then
		pkill -f mpv
		mpv --really-quiet --image-display-duration=6000 "${progdir}/res/${HW}_L1.png" &
		KEY=4
	fi
	Test_Button_R1
	if [ "$?" -eq "10" ]; then
		pkill -f mpv
		mpv --really-quiet --image-display-duration=6000 "${progdir}/res/${HW}_R1.png" &
		KEY=5
	fi
	Test_Button_L2
	if [ "$?" -eq "10" ]; then
		pkill -f mpv
		mpv --really-quiet --image-display-duration=6000 "${progdir}/res/${HW}_L2.png" &
		[[ ${MODEL} == "RG35xxH" ]] && KEY=10 || KEY=9
	fi
	Test_Button_R2
	if [ "$?" -eq "10" ]; then
		pkill -f mpv
		mpv --really-quiet --image-display-duration=6000 "${progdir}/res/${HW}_R2.png" &
		[[ ${MODEL} == "RG35xxH" ]] && KEY=11 || KEY=10
	fi
	if [[ ${MODEL} == "RG35xxH" ]]; then
		Test_Button_L3
		if [ "$?" -eq "10" ]; then
			pkill -f mpv
			mpv --really-quiet --image-display-duration=6000 "${progdir}/res/${HW}_L3.png" &
			KEY=9
		fi
		Test_Button_R3
		if [ "$?" -eq "10" ]; then
			pkill -f mpv
			mpv --really-quiet --image-display-duration=6000 "${progdir}/res/${HW}_R3.png" &
			KEY=12
		fi
	fi
	Test_Button_SE
	if [ "$?" -eq "10" ]; then
		pkill -f mpv
		mpv --really-quiet --image-display-duration=6000 "${progdir}/res/${HW}_OFF.png" &
		KEY=66
	fi
	Test_Button_ST
	if [ "$?" -eq "10" ]; then
		[ $KEY -ne 99 ] && break
	fi
	Test_Button_FUNC
	if [ "$?" -eq "10" ]; then
		pkill -f mpv
		pkill -f evtest
		exit 0
	fi
done
if [ $KEY -eq 66 ]; then
	rm -f /mnt/mod/ctrl/configs/tk.cfg
else
	echo -n $KEY > /mnt/mod/ctrl/configs/tk.cfg
fi
pkill -f mpv
mpv --really-quiet --image-display-duration=3 "${progdir}/res/done.png"
pkill -f mpv
pkill -f evtest
exit 0
