#!/bin/bash
# Port-shell hook, after control.txt.
[ -n "$PLATFORM" ] || . /mnt/SDCARD/spruce/scripts/helperFunctions.sh

case "$PLATFORM" in
Anbernic*)
    # gptokeyb needs dll-mali (only build that classifies the pad), and the pad map written for it.
    GPTOKEYB2="$ESUDO env LD_LIBRARY_PATH=/mnt/SDCARD/App/PyUI/dll-mali:$LD_LIBRARY_PATH SDL_GAMECONTROLLERCONFIG=$SDL_GAMECONTROLLERCONFIG LD_PRELOAD=$controlfolder/libinterpose.${DEVICE_ARCH}.so $controlfolder/gptokeyb2 $ESUDOKILL"
    GPTOKEYB="$ESUDO env LD_LIBRARY_PATH=/mnt/SDCARD/App/PyUI/dll-mali:$LD_LIBRARY_PATH SDL_GAMECONTROLLERCONFIG=$SDL_GAMECONTROLLERCONFIG $controlfolder/gptokeyb $ESUDOKILL"

    # Keyboard-driven ports (gptokeyb -c) need the vendor SDL2; pad-driven ones need dll-mali.
    # Must run before the port sources its runtime (love.txt bakes LD_LIBRARY_PATH in).
    if grep -qE '\$GPTOKEYB2?[^&|;]*[[:space:]]-c[[:space:]]' "$0" 2>/dev/null; then
        export LD_LIBRARY_PATH="/mnt/SDCARD/spruce/h700/lib64/sdl2:$LD_LIBRARY_PATH"
        # The pad map is numbered for dll-mali, which puts three phantom keys (ESC, VOL-, VOL+)
        # first; the vendor SDL2 counts the pad from b0. Shift it for ports that read the pad too.
        if [ -n "$SDL_GAMECONTROLLERCONFIG" ]; then
            SDL_GAMECONTROLLERCONFIG="$(printf '%s' "$SDL_GAMECONTROLLERCONFIG" | awk -F, -v OFS=, '{
                for (i = 1; i <= NF; i++)
                    if (match($i, /:b[0-9]+$/) && substr($i, RSTART + 2) + 0 >= 3)
                        $i = substr($i, 1, RSTART + 1) (substr($i, RSTART + 2) - 3)
                print }')"
            export SDL_GAMECONTROLLERCONFIG
        fi
    fi

    # Point SDL at gptokeyb's uinput keyboard once it appears.
    pm_platform_helper() {
        [ -n "$SDL_EVDEV_DEVICES" ] && return 0
        i=0
        while [ "$i" -lt 30 ]; do
            for d in /sys/class/input/event*; do
                [ -r "$d/device/name" ] || continue
                case "$(cat "$d/device/name" 2>/dev/null)" in
                    "Fake Keyboard Mouse"|"Fake Keyboard")
                        export SDL_EVDEV_DEVICES="/dev/input/$(basename "$d")"
                        return 0
                        ;;
                esac
            done
            i=$((i + 1))
            sleep 0.1
        done
        return 0
    }
    ;;
RG351P)
    # 480x320 panel: follow the ArkOS/ROCKNIX RG351P/M convention so ports
    # that branch on these pick their low-res path. control.txt defines
    # get_controls after sourcing the spruce control.txt hook, so it can only
    # be overridden here.
    param_device="anbernic"
    get_controls() {
      LOWRES="Y"
      ANALOGSTICKS=$ANALOG_STICKS
      sdl_controllerconfig="$SDL_GAMECONTROLLERCONFIG"
    }
    ;;
esac
