#!/bin/bash
# unifideck-launcher - Dynamic launcher for Unifideck games
#
# Usage: unifideck-launcher "store:game_id"
#
# This script reads from ~/.local/share/unifideck/games.map
# Format of map file: store:game_id|/path/to/exe|/path/to/workdir
#
# It resets environment variables (LD_LIBRARY_PATH) before launching.

LOG_FILE="$HOME/.local/share/unifideck/launcher.log"
MAP_FILE="$HOME/.local/share/unifideck/games.map"

mkdir -p "$(dirname "$LOG_FILE")"

# Reset environment first
unset LD_LIBRARY_PATH
# Also unset other potentially conflicting vars
unset STEAM_RUNTIME
unset STEAM_COMPAT_CLIENT_INSTALL_PATH

# 1. Get the lookup key (store:game_id)
KEY="$1"

if [ -z "$KEY" ]; then
    echo "[$(date)] Error: No game key provided" >> "$LOG_FILE"
    exit 1
fi

echo "[$(date)] Requesting launch for: $KEY" >> "$LOG_FILE"

# 2. Look up in map file
if [ ! -f "$MAP_FILE" ]; then
    echo "[$(date)] Error: Map file not found at $MAP_FILE" >> "$LOG_FILE"
    exit 1
fi

# Find line starting with KEY|
GAME_ENTRY=$(grep "^$KEY|" "$MAP_FILE" | head -n 1)

if [ -z "$GAME_ENTRY" ]; then
    echo "[$(date)] Error: Game not found in map for key: $KEY" >> "$LOG_FILE"
    exit 1
fi

# 3. Parse entry
# Format: key|exe|workdir
IFS='|' read -r _ EXE_PATH WORK_DIR <<< "$GAME_ENTRY"

if [ -z "$EXE_PATH" ] || [ -z "$WORK_DIR" ]; then
    echo "[$(date)] Error: Invalid map entry: $GAME_ENTRY" >> "$LOG_FILE"
    exit 1
fi

echo "[$(date)] Found game: Exe=$EXE_PATH, Dir=$WORK_DIR" >> "$LOG_FILE"

# 4. Launch
if [ -d "$WORK_DIR" ]; then
    cd "$WORK_DIR"
else
    echo "[$(date)] Warning: Work dir not found: $WORK_DIR" >> "$LOG_FILE"
fi

# Execute
# We use eval to handle potential quotes or complex commands if stored in map
# But typically EXE_PATH is just the path.
exec "$EXE_PATH" "$@"
