#!/usr/bin/bash

# Remove Steam Runtime libraries
unset LD_LIBRARY_PATH

export STEAM_COMPAT=1

exe_name="$(basename "$1")"
exe_dir="$(dirname "$1")"

# Ignore specific executables
if [[ "$exe_name" == "iscriptevaluator.exe" ]] || \
   [[ "$exe_name" == "d3ddriverquery64.exe" ]]; then
    exit 0
fi

# Copy PPDB file from steam_scripts to exe directory if it exists
# Steam passes the appid via SteamAppId environment variable
if [[ -n "$SteamAppId" ]]; then
    # Get PortProton directory from config file or Flatpak defaults
    portproton_dir=""
    new_config_file="$HOME/.config/PortProtonQt.conf"
    legacy_config_file="$HOME/.config/PortProton.conf"
    new_flatpak_id="ru.linux_gaming.PortProtonQt"
    legacy_flatpak_id="ru.linux_gaming.PortProton"
    new_flatpak_config_file="$HOME/.var/app/$new_flatpak_id/config/PortProtonQt.conf"
    new_flatpak_dir="$HOME/.var/app/$new_flatpak_id/data"
    legacy_flatpak_dir="$HOME/.var/app/$legacy_flatpak_id/data"

    if [[ -f "$new_config_file" ]]; then
        portproton_dir="$(awk -F'= ' '/^portdata_path/ {print $2; exit}' "$new_config_file" | tr -d '\n')"
    fi

    if [[ -z "$portproton_dir" ]] || [[ ! -d "$portproton_dir" ]]; then
        if [[ -f "$legacy_config_file" ]]; then
            portproton_dir="$(cat "$legacy_config_file" | tr -d '\n')"
        fi
    fi

    if [[ -z "$portproton_dir" ]] || [[ ! -d "$portproton_dir" ]]; then
        if [[ -f "$new_flatpak_config_file" ]]; then
            portproton_dir="$(awk -F'= ' '/^portdata_path/ {print $2; exit}' "$new_flatpak_config_file" | tr -d '\n')"
        fi
    fi

    if [[ -z "$portproton_dir" ]] || [[ ! -d "$portproton_dir" ]]; then
        if [[ -d "$new_flatpak_dir" ]]; then
            portproton_dir="$new_flatpak_dir"
        elif [[ -d "$legacy_flatpak_dir" ]]; then
            portproton_dir="$legacy_flatpak_dir"
        fi
    fi

    ppdb_source="$portproton_dir/steam_scripts/${SteamAppId}.exe.ppdb"
    ppdb_dest="$exe_dir/${exe_name}.ppdb"

    if [[ -f "$ppdb_source" ]]; then
        cp "$ppdb_source" "$ppdb_dest"
        echo "Copied PPDB from $ppdb_source to $ppdb_dest"
    fi
fi

# Activate virtual environment if available
if [[ -n "$PPQT_VENV_PATH" ]]; then
    cd "$PPQT_VENV_PATH" || exit 1
    source .venv/bin/activate || exit 1
fi

# Use AppImage if specified, then Flatpak if installed, otherwise use portprotonqt from PATH
if [[ -n "$PPQT_BIN_PATH" ]]; then
    "$PPQT_BIN_PATH" --silent --debug-level INFO "$@"
elif command -v flatpak >/dev/null 2>&1 && flatpak info ru.linux_gaming.PortProtonQt >/dev/null 2>&1; then
    flatpak run ru.linux_gaming.PortProtonQt --silent --debug-level INFO "$@"
else
    portprotonqt --silent --debug-level INFO "$@"
fi
