#!/bin/bash
# No double extension
# Extension removed for .cfg : No same game with multiple extension, MyGame.st, MyGame.msa etc.
IFS=$'\n';
GameDevice=""
TosDevice=""
done=0

clear

if [ ! -d "./fd/" ]; then
	echo.
	echo "Can't find 'fd' directory!"
	echo ""
	echo "copy the executable in your hatari folder (the one with games, saves,etc.)."
	echo ""
	echo "exiting..."
	read -n1 -r -p "Press any key to continue..."
fi

if [ -d "./cfg/" ]; then
	echo ""
else
	mkdir ./cfg/
fi

echo ""
echo "This executable will create individual .cfg files for your games."
echo "(for the WiiFlow plugin)"
echo ""
echo "It should be copied in './hatari', the default directory containing 'fd'"
echo "(the floppy disk games)."
echo ""
read -n1 -r -p "Press any key to continue..."

Menu ()
{
	while [ $done != 1 ]
	do
		reply=""
		read -p "" choice
		case $choice in 
			1) 
				reply="sd"
				done=1
		       ;;
		    2) 
				reply="usb"
				done=1
		       ;;
		    q|Q) 
				exit
		       ;;
		    *) 
		       echo "Try again..."
		       ;;
		esac

		if [ "$1" == "game" ]; then
			GameDevice=$reply
		elif [ "$1" == "tos" ]; then
			TosDevice=$reply
		fi
	done
}

clear
echo ""
echo "Where are the games installed? ('fd' directory)"
echo ""
echo "1 - GAMES ON SD"
echo "2 - GAMES ON USB"
echo "q - QUIT"
echo ""
Menu game
done=0

echo ""
echo "Where is the TOS image? (/apps/hatari/tos.img by default)"
echo ""
echo "1 - TOS FILE ON SD"
echo "2 - TOS FILE ON USB"
echo "q - QUIT"
echo ""
Menu tos

echo Creating .cfg files ...

for file in $(find ./fd  -type f -printf "%P\n")
do
	GamePath=${file#fd/}
	GameName="${file##*/}"
	GameName="${GameName%.*}"
	CfgPath="$GameName.cfg"

	sed -e "s;szDiskAFileName =.*;szDiskAFileName = $GameDevice:/hatari/fd/$GamePath;" \
	-e "s;szDiskAZipPath =.*;szDiskAZipPath =;" \
	-e "s;szDiskImageDirectory =.*;szDiskImageDirectory = $GameDevice:/hatari/fd/;" \
	-e "s;szTosImageFileName =.*;szTosImageFileName = $TosDevice:/apps/hatari/tos.img;" \
	-e "s;szHardDiskDirectory =.*;szHardDiskDirectory = $GameDevice:/hatari/hd/;" hatari.cfg > "./cfg/$CfgPath"
done

echo "done"
