#!/bin/sh
read -r current_device </etc/trimui_device.txt

# Arcade Vertical controls fix
BASE="/mnt/SDCARD/Best/Arcade Vertical"
OLD="roms_best_vertival"
NEW="roms_best_vertical"

SRC="$BASE/$OLD"
DEST="$BASE/$NEW"

/mnt/SDCARD/System/usr/trimui/scripts/infoscreen2.sh -m "Applying Update..." -fs 12 -fi 0 -sp &

[ -f /mnt/SDCARD/System/usr/trimui/res/osd/osdlayout.json ] && rm /mnt/SDCARD/System/usr/trimui/res/osd/osdlayout.json

if [ -d "$SRC" ]; then
    rm -f "$SRC/${OLD}_cache7.db"
    mv "$SRC" "$DEST"
    mv "/mnt/SDCARD/RetroArch/.retroarch/config/remaps/FinalBurn Neo/$OLD.rmp" \
        "/mnt/SDCARD/RetroArch/.retroarch/config/remaps/FinalBurn Neo/$NEW.rmp" 2>/dev/null
    sed -i "s|\"rompath\":\"./$OLD\"|\"rompath\":\"./$NEW\"|" "$BASE/config.json"
    sync
fi

# patching language files for MainUI device specific texts
/mnt/SDCARD/System/usr/trimui/scripts/lang_patches.sh "$current_device"

# copy of the most up-to-date version of retroarch for this device
files=$(ls /mnt/SDCARD/RetroArch/ra64.trimui_${current_device}_*.bin 2>/dev/null)
latest_file=$(echo "$files" | sort -V | tail -n 1)
cp "$latest_file" "/mnt/SDCARD/RetroArch/ra64.trimui"

# DC customization
cp /mnt/SDCARD/Emus/DC/config_${current_device}.json /mnt/SDCARD/Emus/DC/config.json
/mnt/SDCARD/System/bin/7zz x /mnt/SDCARD/Emus/DC/flycast_v2.5/flycast_${current_device}.7z -o/mnt/SDCARD/Emus/DC/flycast_v2.5/ -y

# Upgrade the stock OSD
cp -a /mnt/SDCARD/System/usr/trimui/res/osd/. /usr/trimui/osd/
find /usr/trimui/osd/ -type f -name "*" -exec chmod a+x {} \;

# OSD customization
cp /mnt/SDCARD/System/usr/trimui/res/osd/osdlayout_${current_device}.json /usr/trimui/osd/osdlayout.json
# OSD binaries
chmod a+x /usr/trimui/osd/trimui_osdd
cp /mnt/SDCARD/System/usr/trimui/osd/cpuinfo_osdd_${current_device} /mnt/SDCARD/System/usr/trimui/osd/cpuinfo_osdd
cp /mnt/SDCARD/System/usr/trimui/osd/nightmode_osdd_${current_device} /mnt/SDCARD/System/usr/trimui/osd/nightmode_osdd

# Fix PortMaster app
/mnt/SDCARD/System/bin/7zz x -aoa "/mnt/SDCARD/System/updates/portmaster_fix.7z" -o"/mnt/SDCARD"

sleep 2
pkill -9 presenter

sync

rm "$0"
