#!/bin/sh
export LD_LIBRARY_PATH="/mnt/SDCARD/System/lib:/usr/trimui/lib:$LD_LIBRARY_PATH"
read -r current_device </etc/trimui_device.txt
Current_Theme=$(/usr/trimui/bin/systemval theme)
Current_bg="$Current_Theme/skin/bg.png"
if [ ! -f "$Current_bg" ]; then
    Current_bg="/mnt/SDCARD/trimui/res/skin/transparent.png"
fi

################ CrossMix-OS Version Splashscreen ################
read -r version </mnt/SDCARD/System/usr/trimui/crossmix-version.txt
/mnt/SDCARD/System/usr/trimui/scripts/infoscreen.sh -i "$Current_bg" -m "CrossMix OS v$version" &

################ CrossMix-OS internal storage Customization ################
read -r FW_patched_version </usr/trimui/crossmix-version.txt

if [ "$version" != "$FW_patched_version" ]; then

    if [ -f "/usr/trimui/crossmix-version.txt" ]; then
        CrossMix_Update=1
    else
        CrossMix_Update=0 # CrossMix installation on new device or after firmware udpdate
    fi

    # /mnt/SDCARD/System/usr/trimui/scripts/inputd_switcher.sh
    cp /mnt/SDCARD/System/resources/${current_device}_inputd "/mnt/SDCARD/trimui/app/trimui_inputd"
    chmod +x "$bin_dir/trimui_inputd"
    sync

    # Removing duplicated app
    rm -rf /usr/trimui/apps/zformatter_fat32/

    # making some place in root fs
    rm -rf /usr/trimui/res/sound/bgm2.mp3
    swapoff -a
    rm -rf /swapfile
    cp "/mnt/SDCARD/trimui/res/skin/bg.png" "/usr/trimui/res/skin/"

    # USB Storage app update
    rm "/usr/trimui/apps/usb_storage/"*.png
    cp "/mnt/SDCARD/System/resources/usb_storage/"* "/usr/trimui/apps/usb_storage/"

    # Disable Stock Music app
    mv /usr/trimui/apps/musicplayer/config.json /usr/trimui/apps/musicplayer/config_disabled.json

    # Disable Stock Reader app
    mv /usr/trimui/apps/bookreader/config.json /usr/trimui/apps/bookreader/config_disabled.json

    case "$current_device" in
    tsp) ;;
    tsps)
        # fix GL symbolic links for mali drivers
        cd /usr/lib
        ln -s libmali.so libIMGegl.so
        ln -s libmali.so libGLES_CM.so
        ln -s libmali.so libGLESv1_CM.so
        ln -s libmali.so libGLESv2.so
        ln -s libmali.so libglslcompiler.so
        ln -s libmali.so libsrv_um.so
        ln -s libmali.so libusc.so
        ;;
    brick) ;;
    *) ;;
    esac

    # add language files
    if [ ! -e "/usr/trimui/res/skin/pl.lang" ]; then
        cp "/mnt/SDCARD/trimui/res/lang/"*.lang "/usr/trimui/res/lang/"
        cp "/mnt/SDCARD/trimui/res/lang/"*.short "/usr/trimui/res/lang/"
        cp "/mnt/SDCARD/trimui/res/lang/"*.png "/usr/trimui/res/skin/"
    fi

    # custom shutdown script for "Resume at Boot"
    cp "/mnt/SDCARD/System/usr/trimui/bin/kill_apps.sh" "/usr/trimui/bin/kill_apps.sh"
    chmod a+x "/usr/trimui/bin/kill_apps.sh"

    # custom sshd initd script & disabled by default
    cp "/mnt/SDCARD/trimui/etc/init.d/sshd" /etc/init.d/sshd
    chmod a+x /etc/init.d/sshd
    /etc/init.d/sshd disable

    # fix retroarch path for PortMaster
    cp "/mnt/SDCARD/System/usr/trimui/bin/retroarch" "/usr/bin/retroarch"
    chmod a+x "/usr/bin/retroarch"

    # custom shutdown script, will be called by MainUI
    # cp "/mnt/SDCARD/System/bin/shutdown" "/usr/bin/poweroff"
    # chmod a+x "/usr/bin/poweroff"

    # modifying default theme to impact all other themes (Better game image background)
    cp "/mnt/SDCARD/trimui/res/skin/ic-game-580.png" "/usr/trimui/res/skin/ic-game-580.png"

    # Fnkey app modifications
    CrossMixSourceDir="/mnt/SDCARD/System/usr/trimui/res/apps/fn_editor"
    FWappDir="/usr/trimui/apps/fn_editor"
    FWsceneDir="/usr/trimui/scene"

    mkdir -p "$FWappDir" "$FWsceneDir"

    for src in "$CrossMixSourceDir"/*; do
        filename=$(basename "$src")
        app_dest="$FWappDir/$filename"
        scene_dest="$FWsceneDir/$filename"

        # Always copy to the apps directory
        if cp "$src" "$app_dest"; then
            echo "$filename copied to $FWappDir"
            chmod a+x "$app_dest"
        fi

        # Conditional copy to the scene directory (update enabled scene scripts)
        if [ "$CrossMix_Update" = "1" ]; then
            if [ -f "$scene_dest" ]; then
                if cp "$src" "$scene_dest"; then
                    echo "$filename copied to $FWsceneDir"
                    chmod a+x "$scene_dest"
                fi
            fi
        fi
    done

    # On fresh install, always set the default FN function to CPU performance
    if [ ! "$CrossMix_Update" = "1" ]; then
        src="$CrossMixSourceDir/com.trimui.cpuperformance.sh"
        dest="$FWsceneDir/com.trimui.cpuperformance.sh"
        if cp "$src" "$dest"; then
            echo "com.trimui.cpuperformance.sh copied to $FWsceneDir"
            chmod a+x "$dest"
        fi
    fi

    # 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 {} \;

    # Customize SSH sessions
    if ! grep -q "SSH_CONNECTION" /etc/profile; then
        printf '\n\n[ -n "$SSH_CONNECTION" ] || [ -n "$SSH_CLIENT" ] && . /mnt/SDCARD/System/usr/trimui/scripts/ssh_profile.sh\n' >>/etc/profile
    fi

    if [ "$CrossMix_Update" = "0" ]; then # This is a fresh internal firmware
        if -f "/mnt/SDCARD/trimui/firmwares/Last_Automatic_Backup.txt"; then
            Last_Automatic_Backup=$(cat /mnt/SDCARD/trimui/firmwares/Last_Automatic_Backup.txt)
            if [ -f "/mnt/SDCARD/System/backups/firmware_settings/$current_device/$Last_Automatic_Backup" ]; then
                # We have a backup for this device, restoring firmware settings
                "/mnt/SDCARD/Apps/SystemTools/Menu/TOOLS/FW Settings Save-Load.sh" --restore "/mnt/SDCARD/System/backups/firmware_settings/$current_device/$Last_Automatic_Backup" all
            fi
        else
            # No backup, apply default CrossMix theme, sound volume, and grid view
            if [ ! -f /mnt/UDISK/system.json ]; then
                cp /mnt/SDCARD/System/usr/trimui/scripts/MainUI_default_system.json /mnt/UDISK/system.json
            else
                /usr/trimui/bin/systemval theme "/mnt/SDCARD/Themes/CrossMix - OS/"
                /usr/trimui/bin/systemval menustylel1 1
                /usr/trimui/bin/systemval bgmvol 10
            fi
        fi
    fi

    if [ "$Current_Theme" = "../res/" ]; then
        /usr/trimui/bin/systemval theme "/mnt/SDCARD/Themes/CrossMix - OS/"
    fi

    # hide netplay tab in MainUI
    /usr/trimui/bin/systemval netplaytab 0

    # Fix app icons
    "/mnt/SDCARD/Apps/SystemTools//Menu/ADVANCED SETTINGS##APP ICONS (value)/Default.sh"

    # modifying performance mode for Moonlight
    if ! grep -qF "performance" "/usr/trimui/apps/moonlight/launch.sh"; then
        sed -i 's|^\./moonlightui|echo performance > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor\necho 1608000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq\n\./moonlightui|' /usr/trimui/apps/moonlight/launch.sh
    fi

    # we set the customization flag
    rm "/usr/trimui/fw_mod_done"
    echo $version >/usr/trimui/crossmix-version.txt

    ################ CrossMix-OS SD card Customization ################

    # Sorting Themes Alphabetically
    "/mnt/SDCARD/Apps/SystemTools/Menu/THEME/Sort Themes Alphabetically.sh" -s

    # Game tab by default
    if [ "$CrossMix_Update" = "0" ]; then
        "/mnt/SDCARD/Apps/SystemTools/Menu/USER INTERFACE##START TAB (value)/Emulators.sh" -s
    fi

    # Displaying only Emulators with roms
    /mnt/SDCARD/Apps/EmuCleaner/launch.sh -s

    ################ Flash boot logo ################
    if [ "$CrossMix_Update" = "0" ]; then
        case "$current_device" in
        tsp | tsps)
            src_dir="/mnt/SDCARD/Apps/BootLogo/Images_1280x720"
            ;;
        brick)
            src_dir="/mnt/SDCARD/Apps/BootLogo/Images_1024x768"
            ;;
        *)
            src_dir="/mnt/SDCARD/Apps/BootLogo/Images_1280x720"
            ;;
        esac

		SOURCE_FILE="$src_dir/Surwish.bmp"
		"/mnt/SDCARD/Emus/_BootLogo/launch.sh" "$SOURCE_FILE"
    fi

    sync

fi



################ Branding ################
if [ ! -e "/usr/trimui/branding" ]; then
	if [ -e "/mnt/SDCARD/System/usr/trimui/branding" ]; then
		LOG_FILE="/mnt/SDCARD/System/usr/trimui/branding.log"
		exec >$LOG_FILE 2>&1
		brand=$(cat /mnt/SDCARD/System/usr/trimui/branding | head -n 1)
		if [ -z "$brand" ]; then
			echo "No branding configured."

		else
			cp /mnt/SDCARD/System/usr/trimui/branding /usr/trimui/branding
			# cleaning
			echo cleaning
			brandslist="/mnt/SDCARD/System/usr/trimui/brandslist"
			if [ -f "$brandslist" ]; then
				echo cleaning1
				while IFS= read -r branditem; do
					echo cleaning2
					branditem=$(echo "$branditem" | tr -d '\r')
					if [ -n "$branditem" ] && [ "$branditem" != "$brand" ]; then
						rm -rf "/mnt/SDCARD/Themes/$branditem"
						rm -f "/mnt/SDCARD/Apps/BootLogo/Images_1024x768/$branditem.bmp"
						rm -f "/mnt/SDCARD/Apps/BootLogo/Images_1280x720/$branditem.bmp"

						echo Removing "/mnt/SDCARD/Themes/$branditem, /mnt/SDCARD/Apps/BootLogo/Images_brick/$branditem.bmp  and /mnt/SDCARD/Apps/BootLogo/Images_tsp/$branditem.bmp"
					fi
				done <"$brandslist"
				rm -f "$brandslist"
			fi

			# Apply theme
			/usr/trimui/bin/systemval theme "/mnt/SDCARD/Themes/$brand/"

			# Flash logo

			echo "Flashing logo..."
			       case "$current_device" in
        tsp | tsps)
            src_dir="/mnt/SDCARD/Apps/BootLogo/Images_1280x720"
            ;;
        brick)
            src_dir="/mnt/SDCARD/Apps/BootLogo/Images_1024x768"
            ;;
        *)
            src_dir="/mnt/SDCARD/Apps/BootLogo/Images_1280x720"
            ;;
        esac

		SOURCE_FILE="$src_dir/$brand.bmp"
		"/mnt/SDCARD/Emus/_BootLogo/launch.sh" "$SOURCE_FILE"

		fi

	fi
fi
####################################################################


######################### CrossMix-OS at each boot #########################

# override empty password on firmware >= v1.1.1
echo "root:tina" | chpasswd

# Apply current led configuration
/mnt/SDCARD/System/etc/led_config.sh &

######################### Device Type customization #########################

if [ -f "/tmp/device_changed" ]; then
    # 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
    
    # 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
    
fi
sync