#!/bin/sh
source "/var/volatile/project_eris.cfg"

WORKDIR="/var/volatile/launchtmp"

# Clean WORKDIR just in case..
rm -dr "${WORKDIR}"

# Copy files to launchtmp to mimic sonyui launch
cp -r "${PROJECT_ERIS_PATH}/etc/project_eris/SUP/launchers/lzdoom" "${WORKDIR}"

# Continue normal launch script
cd "${WORKDIR}"

echo -n 2 > "/data/power/disable"

${PROJECT_ERIS_PATH}/bin/sdl_input_text_display " " 0 0 12 "/usr/share/fonts/ttf/LiberationMono-Regular.ttf" 0 0 0 "$(pwd)/doom_controller_select.png" XO

SELECTEDOPTION=$?

[ ! -f "${WORKDIR}/.config/lzdoom/lzdoom.ini" ] && cp "${WORKDIR}/.config/lzdoom/lzdoom_def.ini" "${WORKDIR}/.config/lzdoom/lzdoom.ini"

cp "${WORKDIR}/.config/lzdoom/lzdoom.ini" "/tmp/lzdoom_orig.ini"

if [ "${SELECTEDOPTION}" = "100" ]; then
  # Set up controller config according to only one DPAD
  sed -i -e 's/DPadUp=[^"]*/DPadUp=+forward/g' "${WORKDIR}/.config/lzdoom/lzdoom.ini"
  sed -i -e 's/DPadDown=[^"]*/DPadDown=+back/g' "${WORKDIR}/.config/lzdoom/lzdoom.ini"
  sed -i -e 's/DPadLeft=[^"]*/DPadLeft=+left/g' "${WORKDIR}/.config/lzdoom/lzdoom.ini"
  sed -i -e 's/DPadRight=[^"]*/DPadRight=+right/g' "${WORKDIR}/.config/lzdoom/lzdoom.ini"
  sed -i -e 's/Pad_Y=[^"]*/Pad_Y=weapnext/g' "${WORKDIR}/.config/lzdoom/lzdoom.ini"
elif [ "${SELECTEDOPTION}" = "101" ]; then
  # Set up controller config as we have analouge sticks
  sed -i -e 's/DPadUp=[^"]*/DPadUp=togglemap/g' "${WORKDIR}/.config/lzdoom/lzdoom.ini"
  sed -i -e 's/DPadDown=[^"]*/DPadDown=centerview/g' "${WORKDIR}/.config/lzdoom/lzdoom.ini"
  sed -i -e 's/DPadLeft=[^"]*/DPadLeft=weapprev/g' "${WORKDIR}/.config/lzdoom/lzdoom.ini"
  sed -i -e 's/DPadRight=[^"]*/DPadRight=weapnext/g' "${WORKDIR}/.config/lzdoom/lzdoom.ini"
  sed -i -e 's/Pad_Y=[^"]*/Pad_Y=jump/g' "${WORKDIR}/.config/lzdoom/lzdoom.ini"
else
  echo "[ERROR] Couldn't detect controller selection result. RESULT CODE: ${SELECTEDOPTION}" > "${RUNTIME_LOG_PATH}/lzdoom.log"
  exit 1
fi

# Define mods
MODS=" "
for f in "${WORKDIR}/MODS/"*".wad"; do
  [ -e "${f}" ] || continue
  MODS="${MODS} ${f}"
  MODS_LOADED=TRUE
done
[ ! -z "${MODS_LOADED}" ] && MODS=" -file${MODS}"

# Load the first base wad in the WAD directory.
WAD="$(ls ${WORKDIR}/WAD/ | grep -i .wad | head -1)"
[ -z ${WAD} ] && exit 1
WAD="${WORKDIR}/WAD/${WAD}"

chmod +x "lzdoom"

HOME="${WORKDIR}" LD_LIBRARY_PATH="${WORKDIR}/lib" ./lzdoom -iwad ${WAD} ${MODS} &> "${RUNTIME_LOG_PATH}/lzdoom.log"
echo -n 1 > "/data/power/disable"

# Copy changes to config/saves back to launcher dir
cp -r "${WORKDIR}/.config/lzdoom" "${PROJECT_ERIS_PATH}/etc/project_eris/SUP/launchers/lzdoom/.config"

# Clean up WORKDIR 
rm -dr "${WORKDIR}"