#!/bin/sh

progdir=`dirname "$0"`
homedir="/mnt/mmc/CFW/retroarch"
coredir="${homedir}/.retroarch/cores"
logfile="/mnt/mmc/CFW/retroarch/.retroarch/logs/retroarch.log"
romfile=$1
filename=${1##*/}

test_core() {
for core in km_mame2003_xtreme_libretro.so fbneo_libretro.so
do
	run_rom $core $romfile
	case $core in 
	km_mame2003_xtreme_libretro.so)
		if grep "Failed to load content" $logfile || grep "加载游戏失败" $logfile || ! grep "自动保存状态至" $logfile
		then
			continue
		else
			echo "$filename" >> $progdir/mame2003.txt
			user_quit
		fi
	;;
	fbneo_libretro.so)
		if grep "libretro ERROR" $logfile
		then
			user_quit
		else
			echo "$filename" >> $progdir/fbn.txt
			user_quit
		fi
	;;
	*)
	esac
done
}

run_rom() {
cd ${homedir}
HOME=${homedir}/ ${homedir}/retroarch -v -L $coredir/$1 "$2"
}

user_quit() {
sync
quit 0
}

main() {
if grep "$filename" $progdir/fbn.txt
then
	run_rom "fbneo_libretro.so" $romfile
	user_quit
elif grep "$filename" $progdir/mame2003.txt
then
	run_rom "km_mame2003_xtreme_libretro.so" $romfile
	user_quit
else
	run_rom "fbalpha2012_libretro.so" $romfile
	if grep "Cannot load this game" $logfile || grep "加载游戏失败" $logfile
	then
		test_core
	else
		user_quit
	fi
fi
user_quit
}

main
