#!/bin/bash

# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2023-present JELOS (https://github.com/JustEnoughLinuxOS)

# This file can and should be sourced by ports for various parameters to
# minimize script customizations and allow for easier future updates
# like adding additional supported devices.
# Thanks to JohnnyonFlame, dhwz, romadu, and shantigilbert for the
# suggestion and assistance with this.
# Source used for gptokeyb available at
# https://github.com/christianhaitian/gptokeyb
# Source used for oga_controls available at
# https://github.com/christianhaitian/oga_controls

. /etc/profile

directory="roms"
controlfolder="/$directory/ports/PortMaster"
ESUDO=""
ESUDOKILL="-1"
SDLDBUSERFILE="/storage/.config/SDL-GameControllerDB/gamecontrollerdb.txt"
clibs="/usr/lib/compat/"
raloc="/usr/bin"
raconf="--config /storage/.config/retroarch/retroarch.cfg"

case "${QUIRK_DEVICE}" in
  "Anbernic RG552")
    profile="rg552"
    lres="N"
    sticks="2"
  ;;
  "Hardkernel ODROID-GO-Ultra"|"Powkiddy RGB10 MAX 3 Pro")
    profile="s922x"
    lres="N"
    sticks="2"
  ;;
  "Powkiddy x55")
    profile="x55"
    lres="N"
    sticks="2"
  ;;
  "Anbernic RG351M")
    profile="anbernic"
    lres="Y"
    sticks="2"
  ;;
  "Anbernic RG351V")
    profile="anbernic"
    lres="N"
    sticks="1"
  ;;
  "ODROID-GO Advance*"|"Powkiddy RGB10")
    profile="oga"
    lres="Y"
    sticks="1"
  ;;
  "ODROID-GO Super")
    profile="ogs"
    lres="N"
    sticks="2"
  ;;
  *)
    profile="rg552"
    lres="N"
    sticks="2"
  ;;
esac


get_controls() {

    ANALOGSTICKS="${sticks}"
    LOWRES="${lres}"

    param_device="${profile}"

    # Extract GUID of current input
    GUID=$(control-gen | awk 'BEGIN {FS="\""} /^DEVICE/ {print $2;exit}')

    # Set file
    export SDL_GAMECONTROLLERCONFIG_FILE="/tmp/gamecontrollerdb.txt"

    # Now find any controller mapped on emulationstation...
    /storage/.config/PortMaster/mapper.txt ${SDL_GAMECONTROLLERCONFIG_FILE} ${controlfolder}

    # Set compatability libs and run compatability script
    export LD_LIBRARY_PATH=${clibs}

    # Some ports want SDL_GAMECONTROLLERCONFIG, so let's fill it in
    sdl_controllerconfig="$(< "${SDL_GAMECONTROLLERCONFIG_FILE}")"
}

GPTOKEYB="$ESUDO $controlfolder/gptokeyb $ESUDOKILL"
