#!/bin/bash

# ======================================================================
# Diagnostic duplicator - Linux version
# ======================================================================

# Steam App ID of the game (Elden Ring = 1245620)
APP_ID="1245620"

# Relative path to the executable from inside the 'mod' folder
# (as found in the .lnk: .\menu\deploy\Gideon.exe)
EXE_REL_PATH="menu/deploy/Gideon.exe"
# Arguments to pass to Gideon
EXE_ARGS="--user --project ELDENVINS"

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BASE="$SCRIPT_DIR"
TARGET="$BASE/mod/parts"

echo
echo "Base folder:   \"$BASE\""
echo "Target folder: \"$TARGET\""
echo

if [ ! -d "$TARGET" ]; then
    echo "The folder \"$TARGET\" does not exist."
    echo "Make sure this script is next to the 'mod' folder and that 'mod/parts' exists."
    read -p "Press any key to continue..."
    exit 1
fi

echo "Listing root content of \"$TARGET\":"
ls -1 "$TARGET" 2>/dev/null || echo "(none)"
echo

echo "Listing all .dcx files in \"$TARGET\":"
ls -1 "$TARGET"/*.dcx 2>/dev/null || echo "(none)"
echo

echo "Listing files containing 'partsbnd' inside \"$TARGET\":"
ls -1 "$TARGET"/*partsbnd*.dcx 2>/dev/null || echo "(none)"
echo

echo "Recursive search (includes subfolders):"
find "$TARGET" -type f -name "*.dcx" 2>/dev/null || echo "(none)"
echo

echo "--------------------------------------------------"
echo "Processing files recursively..."
echo "--------------------------------------------------"

count=0

# Use find to safely handle filenames with spaces/special characters
while IFS= read -r -d '' file; do
    echo
    echo "Found: \"$file\""

    # Extract directory, full basename, and basename without the .dcx extension
    dir=$(dirname "$file")
    fullname=$(basename "$file")
    base_no_dcx="${fullname%.dcx}"          # e.g., "some.partsbnd" or "other_l.partsbnd"

    # 1) Skip if this is already a duplicated _l file
    # We check whether base_no_dcx ends with "_l.partsbnd"
    if [[ "$base_no_dcx" == *_l.partsbnd ]]; then
        echo "    -> Already an _l file; skipping."
        continue
    fi

    # 2) Check for .partsbnd.dcx pattern (i.e., file ends with ".partsbnd.dcx")
    if [[ "$fullname" == *.partsbnd.dcx ]]; then
        echo "    -> Matches *.partsbnd.dcx"
        ((count++))

        # Extract the part before ".partsbnd"
        # e.g., "some.partsbnd" -> basepart="some"
        basepart="${base_no_dcx%.partsbnd}"
        if [ "$basepart" = "$base_no_dcx" ]; then
            echo "        ERROR: Could not extract base from \"$base_no_dcx\""
        else
            newname="${basepart}_l.partsbnd.dcx"
            # 3) If duplicate already exists, skip
            if [ -e "$dir/$newname" ]; then
                echo "        Duplicate already exists: \"$dir/$newname\""
            else
                echo "        Copying to: \"$dir/$newname\""
                cp "$file" "$dir/$newname"
                if [ $? -ne 0 ]; then
                    echo "        ERROR while copying \"$file\""
                else
                    echo "        OK"
                fi
            fi
        fi
    else
        echo "    -> Does not match .partsbnd.dcx; ignored."
    fi
done < <(find "$TARGET" -type f -name "*.dcx" -print0)

echo
echo "Total processed: $count"
echo
read -p "Press any key to continue... (Make sure you have protontricks for next step)"

# ----------------------------------------------------------------------
# Launch the target executable using protontricks-launch
# ----------------------------------------------------------------------
echo
echo "Launching Gideon.exe with protontricks-launch..."

# Check if protontricks-launch is available
if ! command -v protontricks-launch &> /dev/null; then
    echo "ERROR: protontricks-launch not found. Please install protontricks:"
    echo "  - For Debian/Ubuntu: sudo apt install protontricks"
    echo "  - For Arch: sudo pacman -S protontricks"
    echo "  - For other distros, see https://github.com/Matoking/protontricks"
    echo
    echo "You can also manually run the command from the 'mod' folder:"
    echo "  cd \"$BASE/mod\""
    echo "  protontricks-launch --appid $APP_ID \"./$EXE_REL_PATH\" $EXE_ARGS"
    read -p "Press any key to exit..."
    exit 1
fi

# Check if the executable exists
if [ ! -f "$BASE/mod/$EXE_REL_PATH" ]; then
    echo "WARNING: Executable not found at: $BASE/mod/$EXE_REL_PATH"
    echo "Skipping launch."
    read -p "Press any key to exit..."
    exit 0
fi

# Save current directory, then cd into mod folder, no idea if it matters but just in case
ORIG_DIR=$(pwd)
cd "$BASE/mod" || {
    echo "ERROR: Could not change to '$BASE/mod'"
    exit 1
}

# Launch using protontricks-launch
echo "Running: protontricks-launch --appid $APP_ID ./$EXE_REL_PATH $EXE_ARGS"
protontricks-launch --appid "$APP_ID" "./$EXE_REL_PATH" $EXE_ARGS

# Capture exit code
LAUNCH_EXIT=$?

# Return to original directory
cd "$ORIG_DIR" || echo "Warning: Could not return to original directory."

if [ $LAUNCH_EXIT -eq 0 ]; then
    echo "protontricks-launch finished successfully."
else
    echo "protontricks-launch exited with error code $LAUNCH_EXIT."
    echo "Check that the App ID is correct and that the game's Proton prefix exists."
fi

echo
echo "Script finished."
read -p "Press any key to exit..."
exit 0
