#!/bin/sh

# Uncomment the following line to get debug info
#set -x

LOCK_FILE="/var/lock/launcher.lock"
INSTANT_PLAY_FILE="/mnt/instant_play"
RESUME_PLAY_FILE="/mnt/resume_play"
PREVENT_LAUNCHER_FILE="/mnt/prevent_launcher"
REBOOTING_FILE="/run/rebooting"


if [ -f "${LOCK_FILE}" ]; then
    echo "${LOCK_FILE} already exists"
    exit 1
fi
touch "${LOCK_FILE}"

# Sanity cmd: in case these files do not exist
mkdir -p "${MEDNAFEN_HOME}"
cp "/usr/games/lynxboot.img" "/usr/games/mednafen-09x.cfg" "${MEDNAFEN_HOME}/"

# Launch Previous Game if any
if [ -f "${INSTANT_PLAY_FILE}" ]; then
    echo "Found Instant Play file, restarting previous game with command: "$(head -n 1 "${INSTANT_PLAY_FILE}")
    rm -f "${RESUME_PLAY_FILE}"
    mv "${INSTANT_PLAY_FILE}" "${RESUME_PLAY_FILE}"
    source "${RESUME_PLAY_FILE}"
    rm -f "${RESUME_PLAY_FILE}"
    termfix_all
fi

# Then loop to launch the launcher indefinitely
while true; do
	
    # Check if prevent launcher file present
    if [ -f "${PREVENT_LAUNCHER_FILE}" ]; then
		echo "${PREVENT_LAUNCHER_FILE} file found, not starting launcher" 
		sleep 5
    else
    	LAUNCHER=$(get_launcher)

		if [ ${LAUNCHER} == "gmenu2x" ]; then

		    # Launch gmenu2x
		    gmenu2x&
		elif [ ${LAUNCHER} == "retrofe" ]; then

		    # Launch Retrofe
		    retrofe&
		else
			DEFAULT_LAUNCHER=retrofe
		    echo "Not recognized launcher: $LAUNCHER, setting $DEFAULT_LAUNCHER"
		    set_launcher $DEFAULT_LAUNCHER
		fi

		# Record the PID into a file, wait for the
		# process to terminate and erase the recorded PID
		record_pid $!
		wait $!
		erase_pid

		# In case retrofe quits with errors, clear graphic VT
		termfix_all
    fi

    # WD to prevent 100% CPU
    sleep 0.5

    # Exit if console rebooting
    if [ -f $REBOOTING_FILE ]; then
    	break
    fi
done

# Remove lock file and exit
rm "${LOCK_FILE}"
exit 0
